Data Structures Interview Questions

  1. Find the largest int value in an int array (try to not use native functionality like “max()”)
    	public static int max(int [] array) {
    		int max = Integer.MIN_VALUE;
    		for (int ii = 0; ii < array.length; ii++) {
    			if (array[ii] > max)
    				max = array[ii];
    			if (max == Integer.MAX_VALUE)
    				break;
    		}
    		return max;
    	}
  2. What’s the difference between a stack and a queue?
     
    Stacks are LIFO, i.e. last in, first out. You push things on top of the stack and pop them off the stack.
    Queues are FIFO, i.e. first in, first out. You push things in one side, pop them off the other.
     
  3. Write a function to reverse a string (try to not use native functionality like strrev() or text[::-1])
             char * strrev(char * str) {
               int ii = 0, jj = strlen(str) - 1;
               char tmp;
               while (ii < jj) {
                 tmp = str[ii];
                 str[ii++] = str[jj];
                 str[jj--] = tmp;
               }
               return str;
             }
  4. Write a function that determines if two strings are anagrams. From wikipedia: an anagram is “the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.” (“abc” “bac” “cba” are anagrams, “abc” and “bba” are not)
  5. /**
     * Returns 1 if it's an anagram, 0 otherwise.
     */
    int anagram(char * str1, char * str2) {
    
      // quick check
      if (strlen(str1) != strlen(str2)) {
        return 0;
      }
    
      // copy str2 to our tmp
      char * tmp = malloc(strlen(str2) + 1);
      strcpy(tmp, str2);
    
      int ii = 0;
      while (str1[ii] != 0) {
        char * ch = strchr (tmp, str1[ii]);
    
        // if not found return -1 to indicate not an anagram
        if (ch == 0)
          return 0;
    
        // remove this found letter from second string
        ch[0] = 0;
        if (ch == tmp) {
          tmp = ch + 1;
        } else if (*(ch+1) != 0) {
          tmp = strcat(tmp, ch+1);
    	}
    
        // go to next character
        ii++;
      }
    
      return 1;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *