← TCS bank

TCS · Question 6 · Dynamic Programming

Word Break Problem

Dynamic ProgrammingC++code⏱ O(n²)💾 O(n)
Service-based

Problem

Check if a string can be segmented into valid words from a dictionary.

Approach

dp[i] marks a segmentable prefix; extend from any good split.

Time O(n²)Space O(n)

How it works

  1. 1dp[i] marks a segmentable prefix.
  2. 2Extend from any good split with a dictionary word.

Sample input / output

Input:
s = "codeleet", wordDict = ["leet", "code"]
Output:
true

Constraints

1 <= s.length <= 300.

Solution — read it, then walk it

Time O(n²)Space O(n)Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
STARTinclude <iostream>include <string>include <vector>include <unordered_set>using namespace stdbool wordBreak(conststring& s, constvector<string>& wordDict)DEFINE main()vector<string> dict ={"leet", "code"}cout << boolalpha <<wordBreak("codeleet", dict)<< endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/11

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