Construct the Array from HackerRank
"Impossible" check

Per task description, k &gt;= 2 and n &gt;= 3. But nevertheless you're performing this "impossible" check:

if (n &lt; 3 || k &lt; 2) return 0;


Redundant check

I don't understand why you're checking cases n == 3 separately. You could remove these 2 checks and have this case handled in your for loop quite easily as below (please note that the values of i, countOne and countOther have changed):

long countOne = 0, countOther = 1, temp;
for (int i = 3; i &lt; n; i++) {
    temp = countOther * (k - 1) % MOD;
    countOther = (countOne % MOD + countOther * (k - 2) % MOD) % MOD;
    countOne = temp;
} 


Variable naming

countOne or countOther are not a good way to call your variables - their names don't convey their purpose. I'll leave it up to you to come up with better names. 

Excessive modulo operation

You don't have to perform a modulo operation more times than is needed. Given you task constraints, your can perform a modulo operation twice per iteration as below:

temp = countOther * (k - 1) % MOD;
countOther = (countOne + countOther * (k - 2)) % MOD;
countOne = temp;


Reduce scope of temp

As @Barmar correctly pointed out, your temp variable should be local to the for loop. It's not needed anywhere out of it.

Simplify return statements

You don't have to calculate countOne or countOther once you leave the for loop. You can do it all there, just fix your loop condition from i &lt; n to i &lt;= n and swap countOne with countOther in your return statements.

for (int i = 3; i &lt;= n; i++) {
    long temp = countOther * (k - 1) % MOD;
    countOther = (countOne + countOther * (k - 2)) % MOD;
    countOne = temp;
}

if (x == 1) {
    return countOne;
}

return countOther;


Final Code

public static long countArray(int n, int k, int x) {

    long countOne = 0, countOther = 1;
    for (int i = 3; i &lt;= n; i++) {
        long temp = countOther * (k - 1) % MOD;
        countOther = (countOne + countOther * (k - 2)) % MOD;
        countOne = temp;
    }


    return x == 1 ? countOne : countOther;
}