Monday, August 3, 2015

#codingexercise
Design an algorithm to lay out cells on phone keyboards in order to minimize key presses.
Given the current layout on the phone dialpad, let us see why is it not sufficient. To spell the word snow, we need to press the key 7  four times to advance the letter to be typed to s followed by the 6 key twice to spell n followed by the 6 key three times to spell o followed by the 9 key once to spell w. This takes 10 key presses.
Knowing that I and w are the most frequently typed keys, by just interchanging the two letters will reduce the number of key presses.
In other words, if we use greedy choice to find the most frequent letters and place them on a key with the lowest index. followed by another round that can keep the next round of frequent letters on the next lower index and so on.
Therefore we have
int GetMinKeyPress(int keys, int[] frequencies) {

Array.sort(frequencies);
int letters = frequencies.length;
int presses = 0;
for (int I = letters - 1; I >= 0; I--)
{
   int j = letters -I -1;
   presses += frequencies[I] * (j/keys + 1);
}
return presses;
}

Push and pop sequences
If the pushing sequence is {1,2,3,4,5} then {4,5,3,2,1} is a possible popping sequence while {4,3,5,1,2} is not because the last two elements cannot be popped in the order that they were pushed.
Given two sequences, check if push and pop sequences are possible.
bool IsPopSequence(int[] push, int[] pop, int len)
{
   bool ret = false;
   int startPop = 0;
   int nextPop = startPop;
   int startPush = 0;
   int nextPush = startPush;
   var stk = new stack();
   if (push.length == len && pop.length == len && len > 0) {
   while (nextPop - startPop < len)
   {
      while(stk.IsEmpty() == false || stk. top() != Pop[nextPop])
       {
        if (nextPush - startPush == len)
           break;
        stk.Push(Push[nextPush]);
        nextPush++;
        }
        if (stk. top() != Pop[nextPop])
           break;
        stk.Pop();
        nextPop++;
   }
   if (stk.IsEmpty() && nextPop - startPop == len)
       ret = true;
}
   return ret;
 
}

No comments:

Post a Comment