← Infosys bank

Infosys · Question 67 · Dynamic Programming

Word Break

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

Problem

Given a string and dictionary, determine if string can be segmented into dictionary words.

Approach

Use DP to check substring segmentation.

Time O(n^2)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^2)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 stdCLASS SolutionDEFINEbool wordBreak(string s,vector<string>& wordDict)DEFINE main()Solution solvector<string> dict ={"leet", "code"}cout << boolalpha <<sol.wordBreak("codeleet",dict) << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/14

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