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
Isomorphic Strings: Java Solution with Index Tracking
More Relevant Posts
-
Day - 39 Sort Characters by Frequency The problem - Given a string s, sort it in decreasing order based on the frequency of characters. Return the sorted string. Example : s = "tree" → "eert" or "eetr" s = "cccaaa" → "aaaccc" or "cccaaa" Brute force - Count the frequencies of characters in both strings and then sort manually, but the time complexity will be O(n log n). Approach Used - •) Create HashMap to count character frequencies, iterate through the s.toCharArray() and use hm.put(char, hm.getOrDefault(char, 0) + 1). •) Create max heap PriorityQueue with custom comparator, PriorityQueue<Map.Entry<Character, Integer>> pq. •) And the comparator = (a, b) → b.getValue() - a.getValue(). •) Add all entries from HashMap - pq.addAll(hm.entrySet()). •) While pq is not empty. 1 - Poll entry from pq. 2 - Append character repeated by its frequency, String.valueOf(entry.getKey()).repeat(entry.getValue()). •) Return result.toString(). Complexity - Time - O(n + k log k), where n is string length, k is unique characters. Space - O(n), HashMap and result. Note - PriorityQueue with reverse comparator gives us characters in frequency order automatically. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day - 63 Combination Sum III The problem - Find all combinations of k numbers that sum to n, using only numbers 1-9, each number used at most once. Example : k = 3, n = 7 → [[1,2,4]] Brute Force - Generate all C(9, k) combinations, check each sum, still needs to enumerate all combinations. Approach Used - •) Initialize: Call findCombination(k, 1, n, new ArrayList<>(), ans) (start with number 1). •) findCombination(k, num, target, lst, ans), •) If (target == 0 && k == 0), found valid combination, add new ArrayList(lst) to ans and return. •) Recursive case, for num to 9, 1 - If i > target || k <= 0, break. 2 - Add i to lst. 3 - Recurse with k - 1 (need one less number), i + 1 (next number to try), target - i (remaining sum). 4 - Backtrack: remove i from lst. Complexity - Time - O(C(9, k) × k), C(9,k) combinations, k time to copy each. Space - O(k), recursion depth. Note - Loop from 1-9, add number, recurse with k-1 and target-num. Backtrack when target == 0 && k == 0! #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 16 - 100Days of DSA Problem Statement : ✅ Sum of subarrays of size K ✅ Average of subarrays of size K At first, calculating the sum or average of every subarray looked simple… but using nested loops makes it slow and inefficient for large inputs. That’s when I learned about the Sliding Window technique – a powerful optimization used in many real-world and interview problems. 🧠 Approach: Sliding Window Technique 1️⃣ Create a window of size k 2️⃣ Calculate the sum of the first window 3️⃣ Slide the window one step at a time 4️⃣ Subtract the element going out 5️⃣ Add the element coming in Code template to solve similar problems: int maxSum=0,windowSum=0; List<Integer> list = new ArrayList<>(); for(int right=0;right<size;right++) { maxSum = maxSum+arr[right]; } list.add(maxSum); for(int right=size;right<arr.length;right++) { maxSum+=arr[right]; maxSum-=arr[right-size]; list.add(maxSum); } ⏱ Time & Space Complexity Time Complexity: 🟢 O(n) – each element is processed once Space Complexity: 🟢 O(1) – only a few variables used (constant extra space) #Day16 #SlidingWindow #DSA #Java #ProblemSolving #CodingJourney #JavaDeveloper #BackendDevelopment #Algorithms #Consistency
To view or add a comment, sign in
-
Day 92/100 Problem Statement : Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal. Input: s1 = "sea", s2 = "eat" Output: 231 Solution : https://lnkd.in/gm8-CDmm public int minimumDeleteSum(String s1, String s2) { int m = s1.length(), n = s2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (s1.charAt(i) == s2.charAt(j)) { dp[i][j] = s1.charAt(i) + dp[i + 1][j + 1]; } else { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]); } } } int total = 0; for (char c : s1.toCharArray()) total += c; for (char c : s2.toCharArray()) total += c; return total - 2 * dp[0][0]; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
Polymorphism isn't magic. It's a Lookup Table. I wrote Java for 3 years before I actually understood how the JVM handles Overriding. I relied on the standard university rule: "Method calls are determined by the actual Object type, not the Reference type." While this explains what happens, it doesn't explain how. I imagined the JVM frantically "searching" up the inheritance tree at runtime—scanning the Child class, then the Parent—until it found the method. Architecturally, that would be a disaster. If the JVM had to search the hierarchy (O(N)) for every method call, Java would be too slow for high-performance systems. The JVM avoids this search entirely using vTables (Virtual Method Tables). The Scenario: Imagine we have class B extends A. A has a method print() B overrides show() but inherits print() The Mechanics (Visualized below): Load Time: When Class B is loaded, the JVM builds a hidden array of function pointers. The "Cheat": Since B inherits print(), the JVM simply copies the memory address from A's table into B's table. Runtime: When you run A obj = new B() and call obj.show(), the JVM follows the object in Heap, jumps to the fixed index in the vTable, and runs the code. As the diagram shows: Solid Arrow: The overridden method points to the new B.show() code. Dashed Arrow: The inherited method points back to the existing A.print() code. The Lesson: Efficient systems rarely rely on runtime decisions if they can pre-calculate the answer at load time. (PS: I share more System Design deep dives like this on X. Link in comments 👇) #Java #JVM #SystemDesign #SoftwareArchitecture
To view or add a comment, sign in
-
-
Day - 62 Generate Parentheses The problem - Given n pairs of parentheses, generate all combinations of well formed parentheses. Example : n = 3 → ["((()))","(()())","(())()","()(())","()()()"] Brute Force - Generate all 2^(2n) combinations, then filter for valid ones, still exponential. Approach Used - •) Initialize: Call DFS(0, 0, "", n, res) (start with 0 open, 0 close, empty string). •) DFS(openP, closeP, s, n, res), 1 - Base case, if openP == closeP == n: add s to res (valid combination) and return. 2 - Recursive First case, if openP < n: add '(', recurse with openP+1. 3 - Recursive Second case, if closeP < openP: add ')', recurse with closeP+1. Complexity - Time - O(4^n / √n), the number of valid combinations. Space - O(n), recursion depth. Note - Track open and close parentheses count. Add '(' if open < n, add ')' if close < open. Recurse until both equal n. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 46/50 – LeetCode POTD 🔍 3. Longest Substring Without Repeating Characters 📊 Medium 🧠 Key Idea (Sliding Window + Two Pointers) Whenever a problem asks for a substring without repeating characters, the best approach is 👉 Sliding Window. ✔️ Use two pointers: left (l) and right (r) ✔️ Use a boolean array (arr[128]) to track characters (ASCII set) ✔️ If the current character is not present in the window ➡️ expand the window (r++) ➡️ update the maximum length ✔️ If a duplicate character is found ➡️ shrink the window from the left (l++) ➡️ remove characters until the duplicate is gone ✔️ The window always contains unique characters 📌 Example s = "abcabcbb" ➡️ Longest substring = "abc" ➡️ Output = 3 ⚙️ How the Code Works (Java) arr[ch] = true → character exists in the current window On duplicate → move the left pointer and clear characters Track the answer using maxLen = Math.max(maxLen, r - l + 1) ⚙️ Complexity Analysis ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) (fixed-size array of 128 characters) 💡 Key Takeaway “Substring + uniqueness constraint” ➡️ Think Sliding Window ➡️ Two pointers give an optimal linear-time solution ➡️ Avoid brute force and nested loops 🔁 Consistency beats motivation 🚀 #LeetCode #DSA #SlidingWindow #TwoPointers #Strings #Java #ProblemSolving #CodingJourney #50DaysChallenge
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟱/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 345. Reverse Vowels of a String 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Easy 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given a string s, reverse only the vowels in the string and return it. The vowels are a, e, i, o, and u, and they can appear in both lowercase and uppercase, more than once. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Convert the string into a character array and define a string containing all vowels in both uppercase and lowercase. Use the two-pointer approach by initializing the start and end indices as 0 and array.length - 1. Use a while loop that runs as long as start < end. Inside the loop, use nested while loops to move the start pointer forward and the end pointer backward until they point to vowels. Once both pointers are at vowel positions, swap the characters, then increment start and decrement end. After the loop completes, all vowels in the string will be reversed. Finally, convert the character array back into a string and return the result. I initially thought of using the String.replace() method, but since it replaces all occurrences of a character, it would lead to incorrect output. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), due to single traversal of the array • Space Complexity: O(n), since a new character array is used 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: This mistake pushed me to revisit Java string functions in detail. I learned the differences between String.replace() and replaceAll(), how they work, and understood their parameters and use cases more clearly. A small mistake led to better conceptual clarity. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/gb_6xv4Z #Day5of75 #LeetCode75 #MachineLearning #DataScience #Python #Java #DSA #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
Day - 54 Copy List with Random Pointer The problem - A linked list has next and random pointers. Deep copy the list (create new nodes with same values and pointer relationships). Example : [[7,null],[13,0],[11,4],[10,2],[1,0]] → deep copied list Approach Used - •) Create HashMap<Node, Node> oldToNew. •) Traverse original list (curr = head) 1 - For each node, create new node with same value. 2 - Store mapping, oldToNew.put(curr, new Node(curr.val)). 3 - Move curr forward. •) Traverse original list again (curr = head) 1 - Set next, oldToNew.get(curr).next = oldToNew.get(curr.next). 2 - Set random, oldToNew.get(curr).random = oldToNew.get(curr.random). 3 - Move curr forward. •) Return oldToNew.get(head). Complexity - Time - O(n), two passes. Space - O(n), HashMap stores n mappings. Note - Use HashMap to store old→new node mapping. First pass creates nodes, second pass sets pointers #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟮𝟳/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 394. Decode String 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given an encoded string, return its decoded string. The encoding rule is k[encoded_string], where the encoded string inside the square brackets is repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, and the original data does not contain any digits. Digits are used only for repeat counts. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: A recursive depth-first approach with a global index is used to traverse the string. While iterating through the characters, build the repeat count when a digit is encountered. When an opening bracket [ appears, recursively decode the substring inside it. Once the closing bracket ] is reached, the decoded inner string is repeated k times and appended to the current result. This recursive structure naturally handles nested encoded patterns while maintaining a single traversal over the string. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), where n is the length of the string • Space Complexity: O(n), due to recursion depth and string construction 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Recursive parsing with a shared index is a clean and effective alternative to stacks when solving problems involving nested string decoding. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/giV4yAAG #Day27of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development