## Yahoo Interview Question

Backend Developers**Country:**United States

**Interview Type:**Written Test

1- Compare current and next element in array , if current is greater than next then

a- if the diff between these two numbers is 1 then swap

b- else set boolean flag false and break the loop as it can not be sorted

2- If flag is true then print yes else print no

time complexity - O(n)

```
for(int i=0; i < a.length -1 ;i++){
if(a[i] > a[i+1] ){
if(a[i] - a[i+1] == 1){
swap(a,i,i+1);
}else {
flag = false;
break;
}
}
}
if(flag){
System.out.println("Yes");
}else{
System.out.println("No");
}
```

```
var output = "true";
for(var counter = 1; counter<a.length; counter++){
if((a[counter]-a[counter-1])== -1){
a[counter] = a[counter] + a[counter-1];
a[counter-1] = a[counter] - a[counter-1];
a[counter] = a[counter] - a[counter-1];
}
if(a[counter] < a[counter-1]){
output = "false";
break;
}
}
console.log(output);
```

```
while(n<(length(a)-1)){
n = 0
for (i in 1:(length(a)-1)){
print(i)
if (a[i]>a[i+1]) {
ai_temp = a[i] #store a[i] actual value
aj_temp = a[i+1] #store a[i+1] actual value
a[i] = a[i+1]+1 # modifying a[i] to bring the abs diff to 1
#now that a[i] has bee modified, abs diff is 1, i can move a[i+1]
#will double check before calling swap function
if(abs(a[i]-a[i+1])==1) {
#swapping a[i] and a[i+1]
a[i+1] = a[i] #j becomes a[i] modified
a[i] = aj_temp #i becomes a[i+1] original
}
#now swapping is complete previously a[i] has not become a[i+1]
#now I need to adjust the value of new a[i+1] back to the original a[i]
a[i+1] = ai_temp #setting the value of a[i+1] to the original a[i] stored as ai_temp
}else{
#no need to sort, these two elements are already in increasing order
n = n + 1
}
}
}
```

Question sounds to be tricky

- DATA April 11, 2017