𝗠𝗼𝘀𝘁 𝗗𝗦𝗔 𝗽𝗿𝗼𝗯𝗹𝗲𝗺𝘀 𝗮𝗿𝗲 𝘀𝗹𝗼𝘄 𝗯𝗲𝗰𝗮𝘂𝘀𝗲 𝘄𝗲 𝗸𝗲𝗲𝗽 𝘀𝗲𝗮𝗿𝗰𝗵𝗶𝗻𝗴 𝘁𝗵𝗲 𝗽𝗮𝘀𝘁 𝗮𝗴𝗮𝗶𝗻 𝗮𝗻𝗱 𝗮𝗴𝗮𝗶𝗻. There is a faster way. Day 4/30 – DSA Pattern: Hashing (Frequency Map) 🧠 How to spot this pattern If the problem asks: • Frequency or count • Seen before? • Duplicates • Fast lookup • Subarray counts (with Prefix Sum) 👉 Think HashMap 💡 Simple idea Instead of scanning the array again and again: • Store what you have already seen • Store how many times you saw it • Reuse that information instantly 𝗦𝗲𝗮𝗿𝗰𝗵𝗶𝗻𝗴 𝗯𝗲𝗰𝗼𝗺𝗲𝘀 𝗢(𝟭) 𝗶𝗻𝘀𝘁𝗲𝗮𝗱 𝗼𝗳 𝗢(𝗻). ✏️ Pseudocode 𝙢𝙖𝙥 = 𝙚𝙢𝙥𝙩𝙮 𝙢𝙖𝙥 𝙛𝙤𝙧 𝙚𝙡𝙚𝙢𝙚𝙣𝙩 𝙞𝙣 𝙖𝙧𝙧𝙖𝙮: 𝙞𝙛 𝙚𝙡𝙚𝙢𝙚𝙣𝙩 𝙚𝙭𝙞𝙨𝙩𝙨 𝙞𝙣 𝙢𝙖𝙥: 𝙞𝙣𝙘𝙧𝙚𝙖𝙨𝙚 𝙞𝙩𝙨 𝙘𝙤𝙪𝙣𝙩 𝙚𝙡𝙨𝙚: 𝙨𝙩𝙤𝙧𝙚 𝙞𝙩 𝙬𝙞𝙩𝙝 𝙘𝙤𝙪𝙣𝙩 1 🧩 Problems that use this • Two Sum • Frequency of elements • First non-repeating element • Subarray sum equals K • Nice subarrays (Prefix Sum + HashMap) 🔥 One rule to remember If you keep checking the past again and again, store it in a HashMap. Hashing turns: ❌ repeated searching into ✅ instant lookup Tomorrow: Binary Search 👍 if this helped Comment “DSA” to follow the 30-day pattern series. #DSA #ProblemSolving #Java #CodingInterviews #LearningInPublic #30DaysOfDSA
Hashing for Faster Problem Solving with HashMap
More Relevant Posts
-
🔥 Day 304 – Daily DSA Challenge! 🔥 Problem: 🎯 Combination Sum II Given an array of candidate numbers (with possible duplicates) and a target value, return all unique combinations where the chosen numbers sum to the target. 👉 Each number can be used at most once in a combination. 💡 Key Insights: 🔹 This is a classic backtracking + pruning problem. 🔹 Sorting the array is crucial to handle duplicates efficiently. 🔹 Skip repeated elements at the same recursion level to avoid duplicate combinations. 🔹 Once a number exceeds the remaining target, we can stop early (thanks to sorting). 🔹 Always move to i + 1 since each element can be used only once. ⚡ Optimized Plan: ✅ Sort the candidates array ✅ Use backtracking to explore all valid combinations ✅ Maintain a temporary list (cur) for the current path ✅ Add the path to result when target == 0 ✅ Skip duplicates using if (i > idx && a[i] == a[i - 1]) ✅ Backtrack after each recursive call ✅ Time Complexity: O(2ⁿ) in the worst case ✅ Space Complexity: O(n) (recursion stack + current combination) 💬 Challenge for you: 1️⃣ What happens if we remove sorting — how do duplicates affect the output? 2️⃣ How is this problem different from Combination Sum I? 3️⃣ Can you convert this recursive solution into an iterative one? #DSA #LeetCode #Backtracking #Recursion #ProblemSolving #Java #KeepCoding
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 33 of DSA 🚀 | Binary Search Today I worked on one of the most fundamental algorithms in problem solving — Binary Search. 🔹 Task: Given a sorted array, find the index of a target element in O(log n) time. 🔹 Key realization: Binary Search is not about guessing. It’s about eliminating half of the search space at every step. 💡 What I learned: Binary Search works only on sorted arrays Using left, right, and mid pointers helps narrow the search efficiently Calculating mid as left + (right - left) / 2 avoids overflow Clear boundary conditions (left <= right) are critical ⏱ Time Complexity: O(log n) 📦 Space Complexity: O(1) This problem reinforced how mastering basics builds the foundation for advanced algorithms. #DSA #BinarySearch #Java #ProblemSolving #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟔 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problems were all about 𝐛𝐢𝐧𝐚𝐫𝐲 𝐬𝐞𝐚𝐫𝐜𝐡 𝐰𝐢𝐭𝐡 𝐜𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 — not just finding an element, but deciding where to search. ✅ 𝐏𝐫𝐨𝐛𝐥𝐞𝐦𝐬 𝐒𝐨𝐥𝐯𝐞𝐝 📌 Search in Rotated Sorted Array 📌 Find First and Last Position of Element in Sorted Array 🔹 𝐒𝐞𝐚𝐫𝐜𝐡 𝐢𝐧 𝐑𝐨𝐭𝐚𝐭𝐞𝐝 𝐒𝐨𝐫𝐭𝐞𝐝 𝐀𝐫𝐫𝐚𝐲 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Used 𝐦𝐨𝐝𝐢𝐟𝐢𝐞𝐝 𝐛𝐢𝐧𝐚𝐫𝐲 𝐬𝐞𝐚𝐫𝐜𝐡 At each step, identified which half of the array was sorted Narrowed the search space based on where the target could lie 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: ✅ Binary search is about decisions, not comparisons ✅ Understanding sorted halves simplifies rotated arrays 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: ⏱ Time: O(log n) 📦 Space: O(1) 🔹 𝐅𝐢𝐧𝐝 𝐅𝐢𝐫𝐬𝐭 𝐚𝐧𝐝 𝐋𝐚𝐬𝐭 𝐏𝐨𝐬𝐢𝐭𝐢𝐨𝐧 𝐨𝐟 𝐄𝐥𝐞𝐦𝐞𝐧𝐭 𝐢𝐧 𝐒𝐨𝐫𝐭𝐞𝐝 𝐀𝐫𝐫𝐚𝐲 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Performed 𝐭𝐰𝐨 𝐛𝐢𝐧𝐚𝐫𝐲 𝐬𝐞𝐚𝐫𝐜𝐡𝐞𝐬 One to find the leftmost occurrence One to find the rightmost occurrence Adjusted boundaries after finding the target 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: ✅ One problem can require multiple binary searches ✅ Direction control helps find boundaries efficiently 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: ⏱ Time: O(log n) 📦 Space: O(1) 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Binary search isn’t just a technique — it’s a 𝐰𝐚𝐲 𝐨𝐟 𝐭𝐡𝐢𝐧𝐤𝐢𝐧𝐠. On to 𝐃𝐚𝐲 𝟕 🔁🚀 #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day - 61 Subsets II The problem - Given array that may contain duplicates, return all possible unique subsets. Example : candidates = [10,1,2,7,6,1,5], target = 8 → [[1,1,6],[1,2,5],[1,7],[2,6]] Brute Force - Generate all combinations iteratively, still exponential, but less elegant than recursion. Approach Used - •) Sort the nums array.nums.lengthcktrack(0, nums, subset, res). •) Base case, if i == nums.length, reached end, add new ArrayList(subset) to res and return. •) Recursive First case, include nums[i], add to subset, recurse with i+1, backtrack (remove). •) Recursive Second case, exclude nums[i], recurse with i+1 (don't add). Complexity - Time - O(2^n), each element include/exclude. Space - O(n), recursion depth. Note - Sort array. After excluding an element, skip all duplicates before next recursion to avoid duplicate subsets. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge – Day 9 🧠 Problem: Valid Anagram (LeetCode 242) 💡 Problem Statement: Given two strings s and t, return true if t is an anagram of s, and false otherwise. 👉 An anagram means both strings contain the same characters with the same frequency, just arranged differently. 🔍 Example Input: s = "anagram" t = "nagaram" Output: true 🔥 Intuition Brute force idea: Sort both strings and compare them ❌ Time Complexity: O(n log n) But can we do better? 👉 Yes! Use a Frequency Counter (Hashing Concept) Since the strings contain lowercase English letters, we can use an array of size 26. 🛠 Approach (Counting Characters – Optimized) 💡 Key Idea: If both strings have the same length And every character appears the same number of times → Then they are anagrams ✅ ⚙️ Steps: If lengths are different → return false. Create an integer array of size 26. Traverse both strings: Increment count for character in s Decrement count for character in t If all values in the array are 0 → it's an anagram. ⚙️ Complexity ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) (Because array size is fixed at 26) 🧠 Pattern to Remember 👉 Frequency Counting / Hashing Pattern #DSA #LeetCode #Java #CodingInterview #StringProblems #100DaysOfCode
To view or add a comment, sign in
-
-
Day 9 – DSA Journey | Arrays 🚀 Today’s problem helped me understand backtracking with re-use of elements 🔁 and how recursion explores all valid combinations. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • ➕ Combination Sum 🔹 Combination Sum 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • 🔁 Used backtracking to build combinations • 🎯 Reduced the remaining target at each step • ♻️ Reused the same element by passing the current index again • 📌 Stored a valid path only when the remaining target becomes zero 𝐇𝐨𝐰 𝐢𝐭 𝐖𝐨𝐫𝐤𝐬 • ➡️ Start from a given index to avoid duplicate combinations • ➕ Add the current number to the path • 🔽 Recurse with reduced remaining sum • ⏪ Backtrack by removing the last added number 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • 🧠 Backtracking explores all valid paths systematically • ♻️ Passing the same index allows unlimited reuse of elements • 🎯 Base conditions control recursion flow • 🧹 Clean backtracking keeps the solution correct 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • ⏱ Time: Exponential (depends on number of combinations) • 📦 Space: O(target) (recursion depth + path) 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Backtracking isn’t about speed — It’s about exploring all possibilities correctly 🔍 On to Day 10 🔁🚀 #DSA #Arrays #Backtracking #Recursion #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day 47 Problem Statement: Given a positive integer n, return the maximum distance between two consecutive 1s in its binary representation. If there are less than two 1s, return 0. Intuition: When we convert a number to binary, we can traverse bit by bit. Key observation: Every time we find a 1, we compare its position with the previous 1. The maximum difference between these positions is our answer. Core idea: If current bit is 1: distance = current_position - previous_position update max distance We keep track of: prev → previous index of 1 curr → current bit index Approach: We check the least significant bit using: n & 1 Then shift right: n >>= 1 Repeat until n becomes 0. Code: class Solution { public int binaryGap(int n) { int prev = -1; int result = 0; for (int curr = 0; curr < 32; curr++) { if (((n >> curr) & 1) == 1) { if (prev != -1) { result = Math.max(result, curr - prev); } prev = curr; } } return result; } } Time Complexity O(32) → Constant time (We check at most 32 bits for an integer) Space Complexity O(1) → No extra space used #HappyCoding #DSA #Java #BitManipulation #CodingInterview #LeetCode #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
🚀 DSA Daily Challenge – Day 4 🧠 Problem: 1. Two Sum (LeetCode) 💡 Goal: Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target. You may assume: ✔ Exactly one solution exists ✔ You cannot use the same element twice ✔ Return indices (not values) 🔥 Intuition Brute force would check every pair → O(n²) ❌ But we can do better using a HashMap: 👉 For each number, calculate its complement 👉 Check if the complement already exists in the map 👉 If yes → we found the answer 👉 If not → store the current number with its index Why does this work? Because we reduce the lookup time to O(1) using hashing. 🛠 Approach (HashMap – One Pass) • Create a HashMap to store number → index • Traverse the array once • For each element: Compute complement = target - nums[i] If complement exists in map → return indices Else → store current number in map ⚙️ Complexity ⏱ Time Complexity: O(n) Each element is processed once 📦 Space Complexity: O(n) HashMap stores up to n elements #DSA #DataStructures #Algorithms #LeetCode #TwoSum #CodingInterview #SoftwareEngineer #Java #Programming #CodingPractice #InterviewPrep #100DaysOfCode #Developers #TechCareers #HashMap #ProblemSolving #BigO #TimeComplexity #CompetitiveProgramming
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
-
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