Isomorphic Strings: Java Solution with Index Tracking

Day - 35 Isomorphic Strings The problem - Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order. No two characters may map to the same character, but a character may map to itself. Example : s = "egg", t = "add" → true (e→a, g→d) s = "foo", t = "bar" → false (o cannot map to both a and r) Brute force - Try all possible character mappings, exponential complexity. Approach Used - Used Index Tracking Arrays •) Create two arrays of size 200 to store last seen index - indexS[200] tracks last position of each character in s. indexT[200] tracks last position of each character in t. •) Check if lengths are equal - if not, return false. •) Iterate through both strings (index i from 0 to len) •) Get characters: s.charAt(i) and t.charAt(i), check if indexS[s.charAt(i)] != indexT[t.charAt(i)] 1 - If different, the pattern doesn't match → return false. 2 - Update both arrays, indexS[s.charAt(i)] = i + 1, indexT[t.charAt(i)] = i + 1. •) If loop completes, return true. Complexity - Time - O(n), single pass through strings. Space - O(1), fixed-size arrays (200 elements). Note - Track the last position where each character appeared. If patterns don't match, strings aren't isomorphic! #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories