← L&T Mindtree bank

L&T Mindtree · Question 37 · Backtracking

Letter Combinations of Phone Number

BacktrackingJavacode⏱ O(4^n)💾 O(n)
Service-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:
digits = "23"
Output:
[ad, ae, af, bd, be, bf, cd, ce, cf]

Constraints

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

Solution — read it, then walk it

Time O(4^n)Space O(n)Loops 1Branches 2Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static List<String>letterCombinations(Stringdigits)if (digits.isEmpty())return newArrayList<>()String[] mapping = {"", "","abc", "def", "ghi", "jkl","mno", "pqrs", "tuv"…List<String> result = newArrayList<>()backtrack(digits, 0, "",result, mapping)RETURN resultDEFINE static voidbacktrack(String digits,int idx, String current,List<String> result,String[] mapping)if (idx ==digits.length())result.add(current)RETURNfor (char c :mapping[digits.charAt(idx)- '0'].toCharArray())backtrack(digits, idx + 1,current + c, result,mapping)DEFINE static voidmain(String[] args)System.out.println(letterCombinations("23"))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

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