🚀 DSA Journey | Day 4 — Majority Element (LeetCode) Today, I solved the Majority Element problem and focused on improving my approach from a brute force solution to an optimized one. 🔹 🧠 Problem Understanding Given an integer array, the task is to find the element that appears more than ⌊n/2⌋ times. ✔ The problem guarantees that a majority element always exists ✔ Focus is on optimizing the approach efficiently 🔹 ⚙️ Approach 1: Brute Force For each element, I traversed the entire array again to count its frequency If the frequency exceeded n/2, I returned that element ❌ Time Complexity: O(n²) 👉 Works fine but not scalable for large inputs 🔹 ⚡ Approach 2: Optimized (Using HashMap) Stored frequency of elements using a HashMap Identified the element with count greater than n/2 ✔ Time Complexity: O(n) ✔ Space Complexity: O(n) 💡 Significant improvement compared to brute force 🔹 💡 Key Learnings ✔ How to optimize from O(n²) → O(n) ✔ Importance of choosing the right data structure ✔ Better understanding of frequency-based problems #DSA #LeetCode #Java #ProblemSolving #CodingJourney #Day4 #Learning #Algorithms
Optimizing Majority Element Solution with HashMap
More Relevant Posts
-
📘 DSA Journey — Day 26 Today’s focus: Binary Search fundamentals. Problems solved: • Binary Search (LeetCode 704) • Search a 2D Matrix (LeetCode 74) Concepts used: • Binary Search • Search space reduction • Index mapping in 2D arrays Key takeaway: In Binary Search, the idea is to repeatedly divide the search space in half. By comparing the target with the middle element, we eliminate half of the array each time, achieving O(log n) time complexity. In Search a 2D Matrix, the matrix can be treated as a flattened sorted array. Using index mapping: row = mid / cols col = mid % cols we can apply binary search directly on the matrix without extra space. These problems highlight how binary search is not limited to 1D arrays—it can be extended to structured data with proper transformations. Continuing to strengthen fundamentals and consistency in DSA problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🚀 DSA Journey Day 8 — LeetCode :Finding Duplicates in an Array Today’s problem looked simple at first… but the approach made all the difference 👀 🔍 Problem Understanding Given an integer array nums, return all elements that appear exactly twice. ⚡ Brute Force Approach For every element, traverse the entire array Count occurrences Time Complexity: O(n²) ❌ (Not efficient) 🚀 Optimized Approach (Using HashMap) Used a HashMap to store frequency of each element First pass → store counts Second pass → collect elements with frequency = 2 👉 Steps: Traverse the array Store frequency using map.getOrDefault() Iterate over the map If value == 2 → add to result list 🧠 Example Walkthrough Input: [4,3,2,7,8,2,3,1] Map: {1=1, 2=2, 3=2, 4=1, 7=1, 8=1} Output: [2,3] ⏱️ Complexity Analysis Time: O(n) ✅ Space: O(n) 💡 Key Learning Sometimes the problem isn’t hard… choosing the right data structure is what makes it efficient 🔥 ✅ Result ✔️ Accepted (29/29 test cases) ⚡ Runtime: 30 ms 🙏 Staying consistent and improving every day 📌 Consistency beats motivation #DSA #Java #CodingJourney #LeetCode #ProblemSolving #HashMap #100DaysOfCode #PlacementPreparation
To view or add a comment, sign in
-
-
🚀 Day 48 of #100DaysOfCode Solved 295. Find Median from Data Stream on LeetCode 📊 🧠 Key Insight: We need to dynamically maintain numbers and efficiently return the median at any time. A naive approach (like maintaining a sorted list) works but is not optimal for large inputs. ⚙️ Approach Used (Sorted List + Binary Search): 1️⃣ Maintain a sorted list 2️⃣ Insert each incoming number at the correct position using Binary Search 3️⃣ For median: 🔹If size is odd → return middle element 🔹If even → return average of two middle elements ⏱️ Time Complexity: 🔹Insert: O(n) (due to shifting) 🔹Median: O(1) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #Heaps #BinarySearch #Algorithms #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 88 of DSA Problem Solving 💡 Problem Solved: Two Sum II – Input Array Is Sorted 🔍 Problem Idea: Given a sorted array, find two numbers such that they add up to a target. Return their indices (1-based). 🧠 Key Learning: Instead of using HashMap (like in classic Two Sum), we can optimize using the **Two Pointer Approach** because the array is already sorted. ⚡ Concepts Practiced: * Two Pointer Technique * Array Traversal * Greedy Decision Making ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Approach: * Start with two pointers: one at the beginning and one at the end * If sum is too small → move left pointer forward * If sum is too large → move right pointer backward * If sum matches target → return indices 🔥 Real Journey Behind Solution: Initially, I thought of using HashMap (habit from Two Sum 😅), but then realized the sorted property is a huge advantage. Switching mindset to use **two pointers** made the solution cleaner and more optimal. This problem reminded me: 👉 Always look for constraints like “sorted” — they often unlock better solutions. 📌 Takeaway: Smart observation > brute force #Day88 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #TechGrowth #TwoPointers
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 35 Today’s focus: Binary Search with index patterns. Problem solved: • Single Element in a Sorted Array (LeetCode 540) Concepts used: • Binary Search • Index parity (even/odd pattern) • Search space reduction Key takeaway: The array is sorted and every element appears twice except one. A key observation: Before the single element, pairs start at even indices After the single element, this pattern breaks. Using binary search: • If mid is even and nums[mid] == nums[mid + 1], the single element lies on the right side • Else, it lies on the left side (including mid) By leveraging this pattern, we can find the answer in O(log n) time and O(1) space. Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day #13 / 100 — Data Structures & Algorithms Focused on Binary Search (answer space + edge cases) today. Problems solved: • Koko Eating Bananas • Find the Smallest Divisor Given a Threshold • Single Element in a Sorted Array • First Bad Version Key takeaway: Binary search is not just about finding an element — it’s about searching the answer space efficiently. What improved today: • Better handling of edge conditions • Clear understanding of low/high movement • Recognizing monotonic patterns faster Consistency is slowly converting concepts into instinct. #100DaysOfCode #DSA #LeetCode #Java #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Day 8/100 — #100DaysOfLeetCode Another day, another concept unlocked 💻🔥 ✅ Problem Solved: 🔹 LeetCode 73 — Set Matrix Zeroes 💡 Problem Idea: If any element in a matrix is 0, its entire row and column must be converted to 0 — and the challenge is to do this in-place without using extra space. 🧠 Algorithm & Tricks Learned: Instead of using extra arrays, we can use the first row and first column as markers. First pass → mark rows and columns that should become zero. Second pass → update the matrix based on those markers. Carefully handle the first row and first column separately to avoid losing information. ⚡ Key Insight: The matrix itself can act as storage, reducing extra memory usage. 📊 Complexity Analysis: Time Complexity: O(m × n) → traverse matrix twice Space Complexity: O(1) → solved in-place without extra data structures This problem taught me how small optimizations can significantly improve space efficiency. Learning to think beyond brute force every day 🚀 #100DaysOfLeetCode #LeetCode #DSA #MatrixProblems #Algorithms #Java #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
🚀 DSA Preparation 💪 Solved an interesting Array + HashMap problem involving number reversal. Focused on identifying mirror pairs efficiently , minimizing index distance🔥 Great practice for combining hashing with logic building 🚀 🧠 Problem 🔎 Minimum Distance Between Mirror Pairs Given an array nums, a mirror pair is defined as indices (i, j) such that: 👉 i < j 👉 reverse(nums[i]) == nums[j] Return the minimum absolute distance |i - j| among all mirror pairs. 👉 If no such pair exists, return -1. Example Input: nums = [12,21,45,33,54] Output: 1 Input: nums = [120,21] Output: 1 Input: nums = [21,120] Output: -1 ⚡ Key Learning 📌 Use HashMap to store reversed values and their indices 📌 Check for matches while traversing the array 📌 Efficiently minimize distance during traversal 📌 Time Complexity: O(n * d) → n elements, d digits for reversal 📌 Space Complexity: O(n) → storing elements in map Improving DSA with smart hashing techniques 🚀 #DSA #LeetCode #HashMap #Arrays #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
📌 Median of Two Sorted Arrays Platform: LeetCode #4 Difficulty: Hard ⚙️ Approach • Apply binary search on the smaller array for efficiency • Define search space from 0 to n1 • Partition both arrays such that: – Left half contains (n1 + n2 + 1) / 2 elements – Right half contains remaining elements • Identify boundary elements: – l1, l2 → left side elements – r1, r2 → right side elements • Check valid partition: – l1 <= r2 and l2 <= r1 • If valid: – For even length → median = average of max(left) and min(right) – For odd length → median = max(left) • If not valid: – If l1 > r2, move left – Else move right 🧠 Logic Used • Binary Search on partition index • Dividing arrays into balanced halves • Handling edge cases using boundary values • Achieving optimal O(log(min(n1, n2))) time complexity 🔗 GitHub: https://lnkd.in/g_3x55n8 ✅ Day 36 Completed – Revised advanced binary search and partition-based problem. #100DaysOfCode #Java #DSA #ProblemSolving #CodingJourney #Algorithms #DataStructures #LeetCode #CodingPractice #CodeEveryDay #BinarySearch #ArrayProblems
To view or add a comment, sign in
-
-
🚀 DSA Challenge Day 1: Linked List Kicking off our Data Structures & Algorithms journey with one of the most fundamental concepts, Linked Lists. A Linked List is a data structure where elements are stored in nodes, and each node contains a reference (pointer) to the next node. This allows data to be stored in non-contiguous memory locations, unlike arrays. 🔹 Why it matters Linked Lists help us understand how data can be dynamically connected and managed in memory, forming the foundation for many advanced data structures. 🔹 Core Components • Head, starting point of the list • Tail, last node in the list • Node, contains data and reference to next node • Size, total number of elements In Collaboration With Justina Jodimuttu Abraham #DSA #Java #CodingJourney #100DaysOfCode #LearningInPublic #Algorithm Google 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
U have solved this question on 19 March 😂😂