Diff Tool Builder - Problem

Build a text diff tool that compares two strings line by line, showing additions (+), deletions (-), and unchanged lines.

Requirements:

  • Split both strings into lines
  • Compare each line and mark as: unchanged, added (+), or deleted (-)
  • Return an array of strings where each string represents one line with its prefix
  • Unchanged lines have no prefix, additions start with '+', deletions start with '-'

Note: This is a simplified diff tool - you don't need to implement complex alignment algorithms.

Input & Output

Example 1 — Basic Diff
$ Input: text1 = "line1\nline2\nline3", text2 = "line1\nline4\nline3"
Output: ["line1", "-line2", "line3", "+line4"]
💡 Note: Line1 and line3 are unchanged, line2 was deleted from text1, line4 was added in text2
Example 2 — All Changes
$ Input: text1 = "hello\nworld", text2 = "goodbye\nuniverse"
Output: ["-hello", "-world", "+goodbye", "+universe"]
💡 Note: No common lines - all lines from text1 are deleted, all from text2 are added
Example 3 — Empty Text
$ Input: text1 = "", text2 = "new line"
Output: ["+new line"]
💡 Note: Empty first text, so the line in text2 is an addition

Constraints

  • 0 ≤ text1.length, text2.length ≤ 104
  • Each line contains only printable ASCII characters
  • Lines are separated by '\n' character

Visualization

Tap to expand
INPUTText 1line1line2line3Text 2line1line4line3Two text strings to compareline by line for differencesALGORITHM1Build hash set from Text 22Check each Text 1 line in O(1)3Mark as unchanged or deleted4Add remaining as additionsHash Setline1: 1line4: 1line3: 1RESULTDiff Outputline1-line2line3+line4Each line marked withprefix showing its statusKey Insight:Using a hash set for O(1) line lookups eliminates the need to repeatedlyscan through the entire second text, reducing complexity from O(n×m) to O(n+m)TutorialsPoint - Diff Tool Builder | Hash Set Optimization
Asked in
Google 15 Microsoft 12 GitHub 8 GitLab 6
30.8K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen