Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs/Bellman-Ford

Technique · CP 2000

System of Difference Constraints

Each constraint x_v - x_u <= w becomes an edge u -> v of weight w. A solution exists iff there is no negative cycle, and shortest distances from a virtual source give one.

Learn firstBellman-FordPrefix Sum
0%
mastery
0/1 solved
Practise nextSubarray Sum Constraints
IdeaPracticePitfalls

Recognise it

The signal

constraints like 'the sum of a[l..r] lies in [L, R]' (prefix sums as the variables)

  1. 1Brute force

    Search over assignments.

  2. 2The observation

    Recognising that inequalities are edges.

  3. 3Why it works

    d(v) <= d(u) + w(u, v) is exactly x_v - x_u <= w.

Reach for it when

  • +schedule events 'at least / at most k apart'
  • +assign integers satisfying pairwise difference bounds

Not when

  • ×constraints are not differences (ratios, sums of three variables)

Practice

Next

Subarray Sum Constraints

0/1 solved
  • Subarray Sum ConstraintsCSESHard

Pitfalls

Misconceptions

  • !forgetting the virtual source with 0-weight edges
  • !flipping a '>=' constraint without negating the weight
Go deeperresources

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems