Sunday, January 15, 2012

Keypad Question

This question has been asked in interviews of many giant tech companies. The statement is:
Given a string in the form of numbers on a keypad of a mobile phone, print all the combinations of alphabets that are possible if the numbers are typed on a phone. Assume that the numbers 0 and 1 are not typed.
e.g.
input = 3
output = {d, e, f}
input = 24
output = {ag, bg, cg, ah, bh, ch, ai, bi, ci}
The algorithm I used is a simple recursive one in which the characters are chosen according to the input alphabet and the current character being observed as shown below:

#include<iostream>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<stdio.h>
using namespace std;

char digitmap[8][5] = {"abc","def","ghi", "jkl","mno","pqrs","tuv","wxyz"};

int lengths[] = {3, 3, 3, 3, 3, 4, 3, 4};

void PrintCombos(int N, int curr, char input[], char str[])
{
    if(curr==N){
        //cout<<"1"<<endl;
        str[curr] = '\0';
        printf("%s\n", str);
        return;
    }
    else{
        //cout<<"2"<<"\n"<<curr<<"\n";
        for(int i=0; i<lengths[input[curr]-'0'-2] ; i++){
            str[curr] = digitmap[input[curr]-'0'-2][i];
            PrintCombos(N, curr+1, input, str);
            }
        }
}
int main()
{
    char input[] = "23";
    char str[100];
    PrintCombos(2, 0, input, str);
    return 0;
}

0 comments: