[Hacker Rank] Construct the Array

Construct the Array

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
long countArray(int n, int k, int x) {
long long xdp = x == 1 ? 1 : 0, ydp = x == 1 ? 0 : 1;
long long mod = 1e9 + 7;
for(int i = 1; i < n; i++) {
long long nxdp = ydp;
long long nydp = (ydp * (k - 2) % mod + xdp * (k - 1) % mod) % mod;
xdp = nxdp;
ydp = nydp;
}
return xdp;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/15/PS/HackerRank/construct-the-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.