• Customer Support: admin@thealgorists.com
  • Feedback: We are listening to your every feedback, and taking action to constantly improve your learning experience. If you have any feedback, please use this form: https://thealgorists.com/Feedback.
  • If you are a student, email to admin@thealgorists.com to get special student discount.



Problem Statement:


Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.



Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:
Input: digits = ""
Output: []

Example 3:
Input: digits = "2"
Output: ["a","b","c"]

Solution:


  • NOTE: I highly recommend going through the Backtracking chapters in the order they are given in the Index page to get the most out of it and be able to build a rock-solid understanding.


You need to get yourself familiar with Backtracking Template before going through the solution, if you haven't done that already.

Let's say digits[0...(n-1)] is the given phone number.

We can solve this problem by doing an exhaustive search.

We start from digits[i] where i = 0.
Candidates for the i-th character of the solution would all the possible letters for digits[i]. For each of these candidates, candidates for (i + 1)-th character of the solution would all possible letters for digits[i + 1]. We go on doing this till we have processed for the last character of the solutions.

What we just described above is nothing but Backtracking. Using our backtracking template we get the below code:



This is a Premium content. Please subscribe to access the code.
After subscribing please come back and refresh this page.




Don't forget to take in-depth look at the below problems because that is what would make you comfortable with using the backtracking template and master the art of Backtracking:


The above content is written by:

Abhishek Dey

Abhishek Dey

A Visionary Software Engineer With A Mission To Empower Every Person & Every Organization On The Planet To Achieve More

Microsoft | University of Florida

View LinkedIn profile


If you have any feedback, please use this form: https://thealgorists.com/Feedback.




Subscribe to Our Youtube Channel

Follow Us On LinkedIn
wave