← Capgemini bank

Capgemini · Question 37 · Backtracking

Letter Combinations of Phone Number

BacktrackingC++code⏱ 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 2Branches 2Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeat↻ repeatSTARTinclude <iostream>include <string>include <vector>using namespace stdDEFINE backtrack(conststring& digits, int idx,string current,vector<string>& result,vector<string>& mapping)if (idx ==(int)digits.length())result.push_back(current)RETURNDEFINE letters =mapping[digits[idx] - '0']for (char c : letters)backtrack(digits, idx + 1,current + c, result,mapping)vector<string>letterCombinations(stringdigits)DEFINE main()auto r =letterCombinations("23")cout << "["for (size_t i = 0; i <r.size(); ++i)if (i) cout << ", "cout << r[i]cout << "]" << endlRETURN 0END
  • 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