How to get all the combinations of the keypad value in a mobile by backtracking using C#?

The problem of generating all possible letter combinations from mobile keypad digits can be solved efficiently using backtracking. This approach explores all possible paths by making choices, exploring them recursively, and backtracking when a complete combination is formed.

On a traditional mobile keypad, each digit from 2-9 corresponds to a set of letters. The goal is to find all possible combinations when given a sequence of digits.

Mobile Keypad Mapping 2 ABC 3 DEF 4 GHI 5 JKL 6 MNO 7 PQRS 8 TUV 9 WXYZ Example: "23" ? AD, AE, AF, BD, BE, BF, CD, CE, CF

How Backtracking Works

The backtracking algorithm works by −

  • Taking the first digit and trying each possible letter for that digit

  • Recursively processing the remaining digits

  • When all digits are processed, adding the complete combination to results

  • Backtracking to try the next possible letter

Example

using System;
using System.Collections.Generic;

namespace ConsoleApplication {
    public class BackTracking {
        private string GetKeyPadValueBasedOnInput(string digit) {
            Dictionary<string, string> keypad = new Dictionary<string, string>();
            keypad.Add("2", "abc");
            keypad.Add("3", "def");
            keypad.Add("4", "ghi");
            keypad.Add("5", "jkl");
            keypad.Add("6", "mno");
            keypad.Add("7", "pqrs");
            keypad.Add("8", "tuv");
            keypad.Add("9", "wxyz");
            return keypad.GetValueOrDefault(digit);
        }
        
        public void FindSequence(string currentList, string digits, List<string> output) {
            if (digits.Length == 0) {
                output.Add(currentList);
                return;
            } else {
                string digit = digits.Substring(0, 1);
                string letters = GetKeyPadValueBasedOnInput(digit);
                for (int i = 0; i < letters.Length; i++) {
                    char letter = GetCharFromString(letters, i);
                    FindSequence(currentList + letter, digits.Substring(1), output);
                }
            }
        }
        
        private char GetCharFromString(string letters, int value) {
            char[] charArr = letters.ToCharArray();
            return charArr[value];
        }
    }
    
    class Program {
        static void Main(string[] args) {
            BackTracking b = new BackTracking();
            List<string> output = new List<string>();
            b.FindSequence("", "34", output);
            foreach (var item in output) {
                Console.WriteLine(item);
            }
        }
    }
}

The output of the above code is −

dg
dh
di
eg
eh
ei
fg
fh
fi

Using Different Input Digits

Example

using System;
using System.Collections.Generic;

namespace ConsoleApplication {
    public class KeypadCombinations {
        private Dictionary<char, string> keypad = new Dictionary<char, string> {
            {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"},
            {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}
        };
        
        public List<string> GenerateCombinations(string digits) {
            List<string> result = new List<string>();
            if (string.IsNullOrEmpty(digits)) return result;
            
            GenerateHelper("", digits, 0, result);
            return result;
        }
        
        private void GenerateHelper(string current, string digits, int index, List<string> result) {
            if (index == digits.Length) {
                result.Add(current);
                return;
            }
            
            char digit = digits[index];
            if (keypad.ContainsKey(digit)) {
                string letters = keypad[digit];
                foreach (char letter in letters) {
                    GenerateHelper(current + letter, digits, index + 1, result);
                }
            }
        }
    }
    
    class Program {
        static void Main(string[] args) {
            KeypadCombinations kc = new KeypadCombinations();
            
            Console.WriteLine("Combinations for '23':");
            List<string> combinations23 = kc.GenerateCombinations("23");
            foreach (string combo in combinations23) {
                Console.Write(combo + " ");
            }
            
            Console.WriteLine("<br>\nCombinations for '789':");
            List<string> combinations789 = kc.GenerateCombinations("789");
            Console.WriteLine("Total combinations: " + combinations789.Count);
            foreach (string combo in combinations789.GetRange(0, Math.Min(10, combinations789.Count))) {
                Console.Write(combo + " ");
            }
            Console.WriteLine("...");
        }
    }
}

The output of the above code is −

Combinations for '23':
ad ae af bd be bf cd ce cf 

Combinations for '789':
Total combinations: 64
ptw ptx pty ptz puw pux puy puz prw prx ...

Time and Space Complexity

Aspect Complexity Explanation
Time Complexity O(3^N × 4^M) N digits with 3 letters, M digits with 4 letters
Space Complexity O(3^N × 4^M) Space to store all combinations
Recursion Depth O(N) N is the number of input digits

Conclusion

Backtracking provides an elegant solution for generating all keypad combinations by systematically exploring each possibility. The recursive approach naturally handles the decision tree, making choices at each digit position and backtracking to explore alternative paths until all combinations are found.

Updated on: 2026-03-17T07:04:36+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements