← Meta (Facebook) bank

Meta (Facebook) · Question 37 · Backtracking

Letter Combinations of Phone Number

BacktrackingPythoncode⏱ O(4^n)💾 O(n)
Product-based

Problem

You are given a string containing digits 2-9. Return all possible letter combinations from phone keypad.

Approach

DFS over digits, expanding each into its keypad letters.

Time O(4^n)Space O(n)

How it works

  1. 1Map each digit to its letters.
  2. 2DFS appends one letter per digit position.

Sample input / output

Input:
23
Output:
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']

Constraints

0 <= digits.length <= 4; digits 2-9 only.

Solution — read it, then walk it

Time O(4^n)Space O(n)Loops 1Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeatyesnoSTARTdigitsif not digitsRETURN []mapping = ["", "", "abc","def", "ghi", "jkl", "mno","pqrs",res = []DEFINE dfs(i, path)if i == len(digits)res.append(path)RETURNfor c inmapping[int(digits[i])]dfs(i + 1, path + c)dfs(0, "")RETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)digits = next(it)print(letterCombinations(digits))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits