Saturday, July 21, 2012

Interview question(coding) - 2 :

Problem : Given an array, construct another array where i-th element
is the product of all but i-th elementof original array 
Example : array size = 5
          array = 5 1 2 3 4
          resultant array = 24 120 60 40 30
1*2*3*4 = 24, 5*2*3*4 = 120, 5*1*3*4 = 60, 5*1*2*4 = 40, 5*1*2*3 =30
          
#include<stdio.h>
 
int main()
{
  int a[50], b[50], i, j, n, prod;
  printf("Enter the size of the array ( < 50 ): ");
  scanf("%d", &n);
  printf("\nEnter the elements of the array : ");
  for(i = 0; i < n; i++)
    scanf("%d", &a[i]);
 
  for(i = 0; i < n; i++)
  { 
    prod = 1;
    for(j = 0; j < n; j++)
    {
      if(j != i)
        prod = prod * a[j];
    }
    b[i] = prod;
  }
  printf("\nThe resultant array\n");
  for(i = 0; i < n; i++)
    printf("%d ", b[i]);
    
  return 0;
}
Written by

Interview question (coding) : Remove duplicates from a string


Problem : Given a string, remove the duplicate characters.
example: BANANAS -> BANS
         bananas -> bans
         BaNanAs -> BaNnAs
         1232416 - > 12346
         
#include<stdio.h>
 
int main()
{
  char s1[10], s2[10];
  int i, j, c;
  s2[0] = '\0';
 
  printf("Enter the string : ");
  scanf("%s",s1);
 
  for(i = 0; s1[i] != '\0'; i++)
  {
    c = 0;
    for(j = 0; (s2[j] != '\0' && c == 0); j++)
    {
      if(s1[i] != s2[j])
        continue;
      else
        c = 1;
    } 
    if(c == 0)
    {
      s2[j++] = s1[i];
      s2[j] = '\0';
    }
  }
  printf("\nString after removing duplicates:%s\n", s2);

  return 0;
}

Written by