🚀 Day 564 of #750DaysOfCode 🚀 🔍 LeetCode 3488 – Closest Equal Element Queries (Medium) Today’s problem was a really interesting mix of hashing + binary search + circular array logic — exactly the kind of question that tests both intuition and optimization skills. 💡 Problem Summary: Given a circular array nums and some query indices, for each query we need to find the minimum circular distance to another index having the same value. 🧠 Key Insight: Instead of checking every index (which would be too slow ❌), we: Store all indices of each number using a HashMap Use binary search to quickly find the closest neighbors Handle circular distance using: 👉 min(|i - j|, n - |i - j|) ⚡ Optimized Approach: Preprocess indices → O(n) Each query → O(log n) Overall → Efficient for large constraints (1e5) 📌 What I Learned: Circular arrays often require thinking in modulo arithmetic Preprocessing + binary search can drastically reduce complexity Always check edge cases (single occurrence) 🔥 Problems like this remind me that optimization is not about writing more code, but about thinking smarter. #LeetCode #Java #DSA #CodingJourney #ProblemSolving #HashMap #BinarySearch #Tech #SoftwareEngineering #LearnInPublic #Consistency
Closest Equal Element Queries in Circular Array
More Relevant Posts
-
🚀 Day 19 of Consistency – Optimized “Intersection of Two Arrays II” (LeetCode) Today I pushed one step further and solved a variation where duplicates also matter — making it slightly more challenging and interesting. 🔍 Problem Understanding Given two arrays, return their intersection including duplicates. Each element should appear as many times as it shows in both arrays. 🧠 Initial Thought (Brute Force) Compare each element of one array with another Track used elements manually ⛔ Inefficient due to nested loops → O(n × m) ⚡ Optimized Approach (HashMap – Frequency Count) 👉 This time, I used a smarter strategy: Store frequency of elements from nums1 in a HashMap Traverse nums2 If element exists in map and count > 0: Add to result Decrease frequency 💡 Example nums1 = [1,2,2,1] nums2 = [2,2] Output → [2,2] ⏱ Complexity Analysis Time Complexity: O(n + m) Space Complexity: O(n) 📊 Result ✔️ All test cases passed (61/61) ⚡ Runtime: 3 ms 🔥 Beats 95.42% submissions 🧩 Key Learning HashMap is extremely useful for frequency-based problems Handling duplicates = tracking counts properly Small optimization can drastically improve performance 🙏 Grateful for the journey and learning every single day 🔥 Consistency + Optimization = Growth mindset #DSA #Java #LeetCode #CodingJourney #HashMap #ProblemSolving #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
💡 Day 57 of LeetCode Problem Solved! 🔧 🌟 Maximum Distance Between a Pair of Values 🌟 🔗 Solution Code: https://lnkd.in/gSP_QePE 🧠 Approach: • Two-Pointer Strategy: Maintain two indices (i for nums1 and j for nums2) to scan both non-increasing arrays in a single efficient pass. • Greedy Search: If nums1[i] <= nums2[j], calculate j - i and expand j to find the maximum possible distance. If the value in nums1 is too large, move i forward. ⚡ Key Learning: • Leveraging the non-increasing nature of arrays with two pointers eliminates the need for nested loops, reducing complexity from O(N^2) to linear O(N+M). ⏱️ Complexity: • Time: O(n + m) • Space: O(1) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #Algorithms #TwoPointers
To view or add a comment, sign in
-
-
Day 113 - LeetCode Journey Solved LeetCode 222 – Count Complete Tree Nodes ✅ This problem involves counting the total number of nodes in a complete binary tree, where all levels are fully filled except possibly the last, and nodes are as far left as possible. Approach: I implemented a recursive solution to count nodes. For each node, I recursively calculated the number of nodes in the left and right subtrees and added 1 for the current node. Although this solution works correctly, it follows a straightforward traversal approach and does not fully utilize the properties of a complete binary tree. A more optimized approach can reduce time complexity by comparing left and right subtree heights to detect perfect subtrees and compute their node count directly. Complexity Analysis: • Time Complexity: O(n) • Space Complexity: O(h), where h is the height of the tree (recursion stack) Key Takeaways: • Basic tree traversal (DFS) can solve counting problems effectively • Understanding tree properties can help in optimizing solutions further • Complete binary trees allow more efficient approaches than general trees All test cases passed successfully 🎯 #LeetCode #DSA #BinaryTree #Recursion #Java #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 15 of LeetCode Problem Solving Solved today’s problem — LeetCode #49: Group Anagrams 💻🔥 ✅ Approach: HashMap + Sorting ⚡ Time Complexity: O(n * k log k) 📊 Space Complexity: O(n * k) The task was to group strings that are anagrams of each other. 👉 I used a HashMap where: Key = sorted version of string Value = list of anagrams 💡 Key Idea: If two strings are anagrams, their sorted form will be the same. 👉 Core Logic: Convert string → char array Sort the array Use sorted string as key Store original string in map 💡 Key Learning: Transforming data (like sorting strings) can help in identifying patterns and grouping efficiently. Consistency is the key — learning something new every day 🚀 #Day15 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 4 of My LeetCode Journey Solved today’s POTD (Problem of The Day): Closest Equal Element Queries (Medium) 📝 Problem Summary Given a circular array, for each query index, find the minimum distance to another index having the same value. If no such index exists, return -1. 🧠 Intuition Instead of checking every index for each query (brute force), I realized we only need to focus on positions where the same value occurs. 💡 Approach ✔️ Used a HashMap to store: value → list of indices ✔️ For each query: Found the index position using binary search Checked only left and right neighbors (closest possible matches) ✔️ Calculated distance using circular logic: min(|i - j|, n - |i - j|) 📚 Key Learning Smart preprocessing can reduce time complexity significantly In circular arrays, always consider wrap-around distance Nearest element problems often reduce to adjacent comparisons #LeetCode #Day4 #DSA #ProblemOfTheDay #Java #CodingJourney #PlacementPreparation
To view or add a comment, sign in
-
-
🚀 LeetCode Challenge 27/50 💡 Approach: Classic Binary Search The problem itself demands O(log n) — no room for linear search! Binary Search is one of the most fundamental algorithms in computer science, and mastering it is non-negotiable for every developer. 🔍 Key Insight: → Maintain left and right pointers on the sorted array → Calculate mid = left + (right - left) / 2 — NOT (left+right)/2 → Why? (left+right) can cause INTEGER OVERFLOW for large values! → nums[mid] == target → found! → nums[mid] < target → search right half (left = mid+1) → nums[mid] > target → search left half (right = mid-1) 📈 Complexity: ❌ Linear Search → O(n) Time ✅ Binary Search → O(log n) Time, O(1) Space Real impact: For n=1,000,000 → Linear needs 1M comparisons, Binary Search needs just 20! That's the power of logarithms. 🔥 #LeetCode #DSA #BinarySearch #Java #ADA #PBL2 #LeetCodeChallenge #Day27of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #SearchAlgorithm
To view or add a comment, sign in
-
-
🔥 Day 85 of my LeetCode Journey 🔥 📘 Problem: 257. Binary Tree Paths 🎯 Difficulty: Easy 🔹 Problem Statement: Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. 🔹 Approach Used: Use recursion to traverse the tree If a node is a leaf → add its value as a path For non-leaf nodes: Recursively get paths from left subtree Recursively get paths from right subtree Append current node value with "->" to each child path Collect and return all paths 🔹 Key Concepts: Recursion Depth-First Search (DFS) Tree traversal String manipulation 🔹 Learning: This problem strengthens understanding of DFS traversal and how to build paths dynamically during recursion. It also shows how to combine results from subtrees efficiently. ✅ Status: Accepted (Runtime: 5 ms) 📌 Break problems into smaller subproblems — recursion does the rest 🚀 #LeetCode #Day82 #Java #BinaryTree #DFS #Recursion #DSA #ProblemSolving
To view or add a comment, sign in
-
-
Day 51 of Daily DSA 🚀 Solved LeetCode 83: Remove Duplicates from Sorted List ✅ Problem: Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Approach: Used a single pointer traversal since the list is already sorted, making duplicate detection straightforward. Steps: Start from head node Compare current node with next node If values are same → skip next node Else move current pointer forward Continue until end of list Return updated head ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 45.48 MB Sorted input often simplifies the logic — duplicates become adjacent and easy to remove. #DSA #LeetCode #Java #LinkedList #CodingJourney #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
💡 LeetCode 191 — Number of 1 Bits (Hamming Weight) Recently solved an interesting bit manipulation problem that highlights the power of low-level optimization 🚀 🔍 Problem Statement: Given an unsigned integer, count the number of set bits (1s) in its binary representation. 🧠 Key Insight: Instead of checking every bit individually, we can use a clever trick: 👉 n & (n - 1) removes the rightmost set bit in each operation. This allows us to count only the set bits, making the solution more efficient. ⚙️ Approach Used (Brian Kernighan’s Algorithm): Initialize a counter Repeatedly apply n = n & (n - 1) Increment count until n becomes 0 📈 Time Complexity: O(k), where k = number of set bits (faster than checking all 32 bits) 📦 Space Complexity: O(1) ✨ Why this problem is important: Strengthens understanding of bit manipulation Frequently asked in interviews Useful in low-level optimization and system design 💬 Takeaway: Sometimes the best solutions come from understanding how data is represented at the binary level. Small tricks can lead to big optimizations! #LeetCode #DSA #CodingInterview #Java #BitManipulation #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
🔢 Day 47/75: Optimizing with Brian Kernighan’s Algorithm! Today’s challenge was counting the number of "1" bits in an integer. While the naive approach is to check all 32 bits one by one, I implemented a much more elegant solution known as Brian Kernighan’s Algorithm. The Logic: The expression n = n & (n - 1) has a fascinating property: it always flips the least significant set bit (the rightmost 1) to 0. By running this in a loop until $n$ becomes 0, the number of iterations equals exactly the number of set bits. If a number has only three "1" bits, the loop runs 3 times, not 32. The Result: ✅ Runtime: 0 ms (Beats 100.00% of Java users) ✅ Efficiency: $O(k)$ time complexity, where $k$ is the number of set bits. Mastering these bitwise shortcuts is what separates a good solution from a great one! 🚀 #75DaysOfCode #LeetCode #Java #BitManipulation #Algorithms #ComputerScience #Optimization #SoftwareEngineering
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