🚀 DSA Practice – find the first non -repeating character. While solving a string problem related to character frequency, I first thought of using a HashMap. But then I optimized it further by using an array based on ASCII values — which is faster and more memory-efficient. 💡 Optimized Approach (Using ASCII Array) 🔹 Step 1: Use an integer array of size 256 Since characters are stored internally using ASCII values, we can directly use an array where the index represents the character. ```java int[] freq = new int[256]; ``` 🔹 Step 2: Store frequency using ASCII index Traverse the string once and increment the count using the character’s ASCII value. ```java for (char ch : str.toCharArray()) { freq[ch]++; } ``` Here, `ch` automatically converts to its ASCII integer value, making access O(1) without hashing overhead. 🔹 Step 3: Find the required character while preserving order Traverse the string again and check which character has frequency = 1. ```java for (char ch : str.toCharArray()) { if (freq[ch] == 1) { System.out.println("Answer: " + ch); break; } } `` 🧠 Why This is More Optimized Than HashMap ✅ No hashing overhead ✅ Faster lookups (direct index access) ✅ Lower memory usage compared to HashMap objects ✅ Time Complexity: O(n) ✅ Space Complexity: O(1) (fixed array size – 256) This approach shows how understanding how characters are stored internally (ASCII/Unicode) can help write even more efficient code. Small optimizations like this can make a big difference in performance-critical applications. 💯 #DSA #Java #OptimizedCode #ProblemSolving #CodingPractice
Optimized DSA Practice: Finding First Non-Repeating Character with ASCII Array
More Relevant Posts
-
Encode and Decode Strings — DSA Insight Hi all 👋 Today’s problem: Encode and Decode Strings 🎯 Goal Design an algorithm to: - Encode a list of strings into a single string - Decode it back to the original list Constraint: ✔ Original strings may contain any characters ✔ After decoding, exact data must be restored 💡 Core Intuition Main challenge is: ❌ How do we separate strings safely? If we simply join using a delimiter like "#" or ",", it fails because the same character can appear inside the strings. So we need a lossless encoding strategy. 🔹 Wrong Idea (Common Mistake) str1 + "#" + str2 Problem: If string itself contains "#", decoding breaks. This approach is unreliable. 🔹 Correct Approach — Length Based Encoding (Optimal) Instead of relying on separators, store: length + delimiter + string Example: ["cat","dog"] → "3#cat3#dog" Encoding steps: 1. Take each string. 2. Append its length. 3. Add a fixed separator ("#"). 4. Append actual string. 🔓 Decoding Logic While reading encoded string: 1. Read digits until "#" → this gives length. 2. Extract next "length" characters. 3. Add to result list. 4. Move pointer forward. Because we already know length, decoding becomes deterministic. ⏱ Complexity Let total characters = N Encoding: O(N) Decoding: O(N) Space Complexity: O(N) 🔁 Trade-off - Slightly larger encoded string (extra length info). - But guarantees correctness for all characters. In real systems, correctness > small memory overhead. 🕸 Common Traps - Using delimiter directly without length info. - Forgetting multi-digit length (e.g., 12#hello…). - Incorrect pointer movement while decoding. 🧠 Trigger Pattern Whenever you see: ➡️ Serialize / Deserialize ➡️ Encode / Decode ➡️ Save structure into string Think: ✔ Length-based encoding (safe and reversible) If I missed anything or if you have a better approach, please feel free to add it in the comments 🙌 #DSA #LeetCode #Java #Algorithms #ProblemSolving #CodingJourney #InterviewPreparation #SoftwareEngineer
To view or add a comment, sign in
-
👉 Given a string of uppercase English letters, find the number of pairs (i, j) such that: A[i] = 'A' A[j] = 'G' i < j In simple terms, count how many times 'A' appears before 'G' in the string. 🔘 Brute Force Approach (O(n²)) The most straightforward way is to check every pair: for(int i = 0; i < n; i++) { if(arr[i] == 'A') { for(int j = i + 1; j < n; j++) { if(arr[j] == 'G') { ans++; } } } } ---------------------------------------------------------- 🔘 Optimized Approach (O(n)) Instead of checking every pair, we can: Keep track of how many 'A' we have seen so far. Every time we encounter a 'G', add the count of previous 'A' to the answer. int countA = 0; for(int i = 0; i < n; i++) { if(arr[i] == 'A') { countA++; } else if(arr[i] == 'G') { ans += countA; } } #Java #DSA #Algorithms #ProblemSolving #CodingInterview #InterviewPreparation #DataStructures #TimeComplexity #Optimization #SoftwareEngineering #Developers #TechCareers #CodingJourney #LearnToCode #Programming
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟰𝟴/𝟭𝟬𝟬 | 𝗖𝗼𝗻𝘃𝗲𝗿𝘁 𝗕𝗶𝗻𝗮𝗿𝘆 𝗡𝘂𝗺𝗯𝗲𝗿 𝗶𝗻 𝗔 𝗟𝗶𝗻𝗸𝗲𝗱 𝗟𝗶𝘀𝘁 𝘁𝗼 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 Day 48 ✅ — Binary logic meets linked list traversal. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 #𝟭𝟮𝟵𝟬: Convert Binary Number in a Linked List to Integer (Easy) From LeetCode 𝗪𝗵𝗮𝘁 𝗖𝗹𝗶𝗰𝗸𝗲𝗱: Each node represents a binary digit (0 or 1). The head is the most significant bit. So this isn’t just a linked list problem — it’s a 𝗯𝗶𝗻𝗮𝗿𝘆 𝘁𝗼 𝗱𝗲𝗰𝗶𝗺𝗮𝗹 𝗰𝗼𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻 problem wrapped inside linked list traversal. Two key steps: 1️⃣ Compute the length of the list 2️⃣ Traverse again and apply positional binary weights (2^(length-1)) If a node contains 1, add 2^(position) to the result. Classic bit-weight logic. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: 👉 First pass: calculate linked list length 👉 Second pass: • If node value is 1 → add 2^(length-1) • Decrement length 👉 Handle last node separately Time Complexity: O(n) Space Complexity: O(1) Two traversals, constant space, clean logic. 𝗠𝘆 𝗥𝗲𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻: This problem reinforces something important: Linked list questions aren’t always about pointer manipulation. Sometimes they test whether you can layer fundamental concepts (like binary math) on top of traversal mechanics. The more I practice, the clearer patterns become: Traversal is routine. The real thinking is in identifying the hidden concept. 𝗖𝗼𝗱𝗲:🔗 https://lnkd.in/g9TyHZGk 𝗗𝗮𝘆 𝟰𝟴/𝟭𝟬𝟬 ✅ | 𝟱𝟮 𝗺𝗼𝗿𝗲 𝘁𝗼 𝗴𝗼! #100DaysOfCode #LeetCode #LinkedList #Binary #DataStructures #CodingInterview #SoftwareEngineer #Java #Algorithms #TimeComplexity #Programming
To view or add a comment, sign in
-
🔥 Day 309 – Daily DSA Challenge! 🔥 Problem: 🔁 Permutations II Given an array nums that may contain duplicate numbers, return all unique permutations in any order. 💡 Key Insights: 🔹 This is a backtracking problem with an extra twist — duplicates. 🔹 Sorting the array upfront is the key to handling duplicates cleanly. 🔹 Use a used[] boolean array to track which elements are already in the current permutation. 🔹 The golden rule to skip duplicates 👇 👉 If the current number is the same as the previous one and the previous one is not used, skip it. 🔹 This ensures we only generate unique permutations. ⚡ Optimized Plan: ✅ Sort the input array ✅ Use backtracking to build permutations ✅ Track used elements with a boolean array ✅ Add permutation to result when its size equals nums.length ✅ Skip duplicates using: if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; ✅ Backtrack after each recursive call ✅ Time Complexity: O(n! × n) (due to copying permutations) ✅ Space Complexity: O(n) (recursion stack + used array) 💬 Challenge for you: 1️⃣ Why does the condition !used[i - 1] matter for avoiding duplicates? 2️⃣ How would this solution change if all numbers were unique? 3️⃣ Can you generate permutations iteratively instead of using recursion? #DSA #Day309 #LeetCode #Permutations #Backtracking #Recursion #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 21/30 of my Consistency Challenge 🔥 🎯 Just solved "Generate Parentheses" on LeetCode! Problem: Given n pairs of parentheses, generate all combinations of well-formed parentheses. 💡 Key Insights: • This is a classic backtracking problem that explores all valid combinations • The key constraint: at any point, the number of closing parentheses cannot exceed opening ones • Think recursively: at each step, we can either add '(' or ')' based on our current state ✨ My Approach: Used a DFS (Depth-First Search) strategy with backtracking: - Track the count of opening and closing parentheses - Only add '(' if we haven't used all n pairs yet - Only add ')' if closeP < openP (maintains validity) - Base case: when we've used n opening and n closing parentheses Example: For n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] ⏱️ Complexity: • Time: O(4^n / √n) - Catalan number • Space: O(n) - recursion stack depth Status: ✅ Accepted! This problem really reinforces the power of backtracking for generating valid combinations. The constraint checking is what makes this elegant! #LeetCode #CodingChallenge #Algorithms #Backtracking #Java #ProblemSolving #SoftwareEngineering #DSA #TechInterview
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge – Day 19: Reverse Linked List (Easy) 🔁 A foundational linked list problem from LeetCode 206 that tests pointer manipulation and iterative thinking. Simple on the surface — powerful for building core DSA intuition. 🔍 Problem Recap Given the head of a singly linked list, reverse the list and return the new head. You must reverse the direction of links Do it efficiently Return the new starting node 💡 Core Idea Instead of creating a new list, we reverse the links in-place. 1️⃣ Maintain three pointers: prev → tracks the previous node current → the node we’re processing next → temporarily stores the next node 2️⃣ Traverse the list: Store next node Reverse the current node’s pointer Move all pointers one step forward 3️⃣ Continue until the list ends At the end, prev becomes the new head. 🧠 Why This Works Each node’s pointer is reversed exactly once No extra data structures needed Clean in-place transformation Linear traversal ⏱ Time Complexity → O(n) 📦 Space Complexity → O(1) This is one of the best problems to truly understand pointer movement. 🧩 Dry Run Example Original: 1 → 2 → 3 → 4 → 5 → null Step-by-step reversal: 1 ← 2 ← 3 ← 4 ← 5 Final Output: 5 → 4 → 3 → 2 → 1 → null ⚡ Pattern Connection Pointer manipulation Iterative linked list traversal In-place reversal pattern Foundation for advanced problems like: Reverse in K-groups Palindrome Linked List Detect cycle variations Master this, and many linked list problems become easier. #DSA #LeetCode #Day19 #Java #LinkedList #ReverseLinkedList #CodingInterview #ProblemSolving #100DaysOfCode #DataStructures #InterviewPrep #Algorithm #EasyLevel #ProgrammingTips #CodingChallenge #Pointers #InPlace #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 13/100 — Recursive Deconstruction Today’s Challenge: LeetCode 761 - Special Binary String 🧩 Yesterday was about bits; today was about Structural Grammar. Special Binary Strings aren't just 1s and 0s; they are a language. The Realization: A special string is like a valid set of parentheses. 1 is ( and 0 is ). To find the "lexicographically largest" version, you have to break the string into its most basic components, sort them, and put them back together. My 0ms Optimization Strategy: 1. Mental Mapping: Treated the string as a nested structure. If 1...0 is a special string, I stripped the outer layer, solved the inside, and then re-wrapped it. 2. Greedy Reassembly: Used Collections.sort() with a reverse comparator. In binary, "larger" just means the 1s appear as early as possible. 3. Memory Management: Minimized object creation by identifying "split points" first before committing to substring allocations. Reflection: Sometimes the fastest way to solve a problem isn't to iterate forward, but to look at the problem as a recursive tree. Every "Special" chunk is a node that can be reordered to maximize the total value. 13 days down. The logic is getting deeper. 87 days to go. 🛠️ #Java #DSA #LeetCode #100DaysOfCode #Recursion #StringAlgorithms #SoftwareEngineer #CodingJourney #Optimization
To view or add a comment, sign in
-
-
📝 DSA Practice — Top K Frequent Words (LeetCode 692) Today I solved Top K Frequent Words, an interesting variation of the top-k pattern that combines frequency counting with custom ordering logic. 🔍 Key Learnings First step is building a word frequency map. Ranking is based on frequency first, then lexicographical order. Priority queues help maintain the correct top-k ordering efficiently. Custom comparator logic plays a crucial role. 🧠 Why This Problem Matters Frequently asked in coding interviews. Strengthens understanding of hash maps + heaps + custom sorting. Similar patterns appear in search engines and recommendation systems. 📌 Final Takeaway This problem shows that real-world ranking problems often involve multiple sorting conditions, and designing the right comparator makes all the difference. #leetcode #dsa #heap #hashmap #strings #customsorting #problemSolving #codingpractice #java #datastructures #interviewpreparation #100DaysOfCode
To view or add a comment, sign in
-
-
Continued with Arrays today and worked on the Dutch Flag Algorithm to sort an array of 0s, 1s, and 2s in one pass. This problem was less about sorting and more about pointer management. int[] arr = {2, 0, 2, 1, 1, 0}; int low = 0, mid = 0, high = arr.length - 1; while (mid <= high) { if (arr[mid] == 0) { swap(arr, low, mid); low++; mid++; } else if (arr[mid] == 1) { mid++; } else { swap(arr, mid, high); high--; } } for (int x : arr) { System.out.print(x + " "); } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Output: 0 0 1 1 2 2 What this problem highlighted for me: - multiple pointers can work together in a single loop - not every problem needs nested loops - pointer movement depends on what value is found - getting one pointer wrong breaks the entire logic This felt like my first real exposure to a one-pass array algorithm. Continuing with Arrays & ArrayLists today. #Java #DSA #Arrays #LearningInPublic #ProblemSolving #Coding #Programming #DeveloperJourney #JavaDeveloper
To view or add a comment, sign in
-
🚀 Day 503 of #750DaysOfCode 🔥 LeetCode 3714 — Longest Balanced Substring II (Medium) Today’s challenge was all about prefix differences, hashing, and smart optimization. We’re given a string containing only 'a', 'b', and 'c'. A substring is called balanced if all distinct characters in that substring appear the same number of times. 🧠 Key Insight Since we only have 3 characters, instead of brute-forcing every substring (which would be O(n²) ❌), we can: Track prefix counts of a, b, c Store frequency differences Use a HashMap to detect when the same difference pair appears again If two prefixes have the same difference values: (countA - countB) (countB - countC) Then the substring between them is balanced ✅ 💡 Optimization Strategy This solution smartly breaks the problem into 3 cases: 1️⃣ Only one distinct character 2️⃣ Exactly two distinct characters 3️⃣ All three characters Each case is handled efficiently using prefix differences and HashMaps. Time Complexity: O(n) Space Complexity: O(n) No brute force. No nested loops. Just pure prefix logic. 🔥 What I Learned Today ✔ Prefix difference technique is powerful ✔ Hashing states helps avoid O(n²) brute force ✔ Breaking complex problems into structured cases simplifies thinking ✔ Medium problems often test observation, not complexity “The difference between good and great coders is not syntax — it’s pattern recognition.” Onward to Day 504 💪🔥 #LeetCode #DataStructures #Algorithms #Java #CodingJourney #750DaysOfCode #ProblemSolving #TechGrowth
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