Amazon Interview Question
Software Engineer / Developers{void count_item(int a[],int len){
int item, item_count, present_idx;
int i;
i = 0;
present_idx = 0;
item_count = 1;
item = a[i];
for (i=1; i<len; i++) {
if (item ==a[i]) {
item_count++;
}
else {
a[present_idx++] = item;
a[present_idx++] = item_count;
item_count = 1;
item = a[i];
}
}
a[present_idx++] = item;
a[present_idx++] = item_count;
a[present_idx]=0;
for (i=0; i<present_idx; i++) {
if(a[i]==0)
break;
printf("%d ",a[i]);
}
}
}
{void count_item(int a[],int len){
int item, item_count, present_idx;
int i;
i = 0;
present_idx = 0;
item_count = 1;
item = a[i];
for (i=1; i<len; i++) {
if (item ==a[i]) {
item_count++;
}
else {
a[present_idx++] = item;
a[present_idx++] = item_count;
item_count = 1;
item = a[i];
}
}
a[present_idx++] = item;
a[present_idx++] = item_count;
a[present_idx]=0;
for (i=0; i<present_idx; i++) {
if(a[i]==0)
break;
printf("%d ",a[i]);
}
}
}
Problem:
================
given a stream of integers.. 112233344442222 write a function that would return as 1222334424
it takes aabbcccddddbbbb and returns a2b2c3d4b4.
Example:
================
A[aabbcccddddbbbb]
Result: a2b2c3d4b4
ALGO:
================
Take A[i] compare with all and increase the counter
put Str S += A[i] + Counter
Return the complete String
CODE:
================
private string CharCount(Array A[], Int n) \\N IS THE SIZE OF ARRAY
{
FOR(I=0;I<N;I++)
{
FOR(J=0;J<N;J++)
{
IF(a[I]==a[J])
{
COUNT++;
}
ELSE
{
J=N; \\TO KILL THE ITERATIONS
}
}
STRING S += A[I]+COUNT;
}
RETURN s;
}
ORDER:
================
O(N^2)
Another example: it takes aabbcccddddbbbb and returns a2b2c3d4b4.
- Anonymous March 05, 2010