## ahmed.abouhegaza

BAN USER
Comments (2)

Reputation 0

Page:

1

Comment hidden because of low score. Click to expand.

Comment hidden because of low score. Click to expand.

0

of 0 vote

I really can't decide what is the big O for this answer, however I'm pretty sure it is less than O(n^2)

```
public static void main(String args[]) {
method(4, 0);
}
public static void method(int n, int counter) {
if(counter<Math.pow(10, n-1)) method(n,(int)Math.pow(10, n-1));
else if (counter >= Math.pow(10, n)) {
return;
} else {
boolean flag = true;
for (int i = 1; i <= n; i++) {
int current, before, after;
current = getNumber(counter, i);
before = i == n ? current : getNumber(counter, i + 1);
after = i == 1 ? current : getNumber(counter, i - 1);
if (!(Math.abs(current - before) <= 1 && Math.abs(current - after) <= 1))
flag = false;
}
if (flag == true)
System.out.println(counter);
method(n, ++counter);
}
}
public static int getNumber(int number, int position) {
int n = (int) (number % Math.pow(10, position));
n = (int) (n / Math.pow(10, position - 1));
return n;
```

}

- ahmed.abouhegaza October 14, 2017Page:

1

**CareerCup**is the world's biggest and best source for software engineering interview preparation. See all our resources.

Open Chat in New Window

- ahmed.abouhegaza October 18, 2017