Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
No, it does not...
If you iterate with two pointers from front and back...loop will run len/2 at max...even if you consider 2 extra statements for swapping it will be "n".
But in your case we need 2n iterations one for putting all elements in stack another for getting all elements back to array.....since array provides O(1) lookup time you should make use of it....your implementation is a good solution for linked lists.
@rkt -- here your code is wrong for some i/p ex-{1,2,3,4} when u iterate this i/p u find an error.....
correct code is.....
// here len of the array means no of element in that array.....
void reverse(int a[],int len){
int i,temp;
if(len%2==0)
{
len =len-1;
for(i=0;i<(len/2)+1;i++){
temp = a[i];
a[i] = a[len-i];
a[len-i] = temp;
}
}
else
{
for(i=0;i<len/2;i++){
temp = a[i];
a[i] = a[len-1-i];
a[len-1-i] = temp;
}
}
}
#include<stdio.h>
#include<stdlib.h>
void print(int *arr, int len) {
int i;
for (i=0;i<len;i++)
printf("%d, ", arr[i]);
printf("\n");
}
void swap(int *a, int *b) {
int tmp=*a;
*a=*b;
*b=tmp;
}
void reverse(int *arr, int len) {
int i=0;
while (i < len--)
swap(&arr[i++], &arr[len]);
}
int main(void) {
int *arr=NULL;
int size, i;
printf("Enter array size : ");
scanf("%d",&size);
arr=(int *)calloc(size,sizeof(int));
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
print(arr,size);
reverse(arr,size);
print(arr,size);
free(arr);
return 0;
}
Reversing an integer array:
- rkt March 14, 2012