I just recorded myself solving the Contains Duplicate problem and walking through a couple of different approaches. The problem: Given an integer array nums, return true if any value appears more than once. Otherwise, return false. Examples: • [1, 2, 3, 3] → true • [1, 2, 3, 4] → false 💡 Approach 1: Nested Loops (Brute Force) I started with a double loop to compare every pair of elements. ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(1) It works, but it’s not scalable for large inputs. 💡 Approach 2: Sort + Single Pass (Optimized) Then I improved the solution by: 1️⃣ Sorting the array 2️⃣ Looping once to check adjacent elements If nums[i] === nums[i - 1], we’ve found a duplicate. ⏱ Time Complexity: O(n log n) (because of sorting) 📦 Space Complexity: Depends on the sorting implementation I enjoy breaking problems down this way — starting simple, then refining the solution step by step. That’s where real learning happens. Here’s the full walkthrough video: 🔗 https://lnkd.in/efeFYhtC #NeetCode #Algorithms #DataStructures #CodingInterview #JavaScript #SoftwareEngineering #ProblemSolving
Contains Duplicate Problem Solution: Brute Force and Optimized Approaches
More Relevant Posts
-
Solved the classic Reverse Linked List problem on LeetCode today. Approach used: Iterative pointer manipulation. Key idea: Maintain three pointers — prev, curr, and next. Algorithm flow: Store the next node (next = curr.next) Reverse the link (curr.next = prev) Move pointers forward (prev = curr, curr = next) Time Complexity: O(n) Space Complexity: O(1) It’s a simple problem conceptually, but mastering pointer manipulation is essential for understanding linked list internals and many advanced data structure problems. Consistently practicing these fundamentals strengthens problem-solving intuition and prepares you for more complex algorithmic challenges. #leetcode #datastructures #algorithms #javascript #linkedlist #problemSolving #codingPractice
To view or add a comment, sign in
-
-
Problem: Can Make Arithmetic Progression From Sequence ✔️ 113 / 113 test cases passed ✔️ Runtime: 0 ms ✔️ Beats 100% submissions Core Idea: To check if an array can form an Arithmetic Progression (AP), the difference between consecutive elements must remain constant. Instead of sorting the array, I used a more mathematical approach: 1. Find minimum and maximum values. Calculate the expected common difference using { (max−min)/(n−1)(max - min) / (n - 1)(max−min)/(n−1) } If this difference is not an integer, forming an AP is impossible. 2. Use a Set for constant-time lookups. Verify whether every expected element of the progression exists. This avoids sorting and keeps the solution efficient. Complexity: Time Complexity: O(n) Space Complexity: O(n) Sometimes a bit of math + hash sets can replace heavier operations like sorting. #LeetCode #DSA #Algorithms #JavaScript #ProblemSolving #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
🚀 LeetCode: 3Sum The goal is to find all unique triplets in an array that sum up to zero. This is a significant step up from Two Sum, requiring careful handling of duplicates to ensure every triplet in the result is unique. 🛠️ My Approach Sorting for Strategy: I started by sorting the array in ascending order. This is crucial as it allows us to easily skip duplicate values and use a directional two-pointer technique. 🔡 Fixed Element Loop: I iterated through the array, treating each element as a potential first part of a triplet. To optimize, if the current element is greater than zero, I break the loop immediately since no combination of following positive numbers can sum to zero. 🧹 Two-Pointer Optimization: For each fixed element, I used two pointers—one starting just after the fixed element (l) and one at the very end (r). 📍 If the sum is too high, I move the right pointer in. If the sum is too low, I move the left pointer out. When a sum of zero is found, I capture the triplet and then skip any identical adjacent values to avoid duplicate results. ❌ This approach transforms a potential O(n^3) brute-force cubic time complexity into a much more efficient quadratic solution. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n^2) due to the nested two-pointer search inside the main loop. 💾 Space Complexity: O(1) or O(n) depending on the implementation of the sorting algorithm, as we don't use extra data structures for the search itself. Achieving a 91.76% runtime beat on this classic problem! Handling edge cases and duplicates is where the real engineering happens. 🚀👨💻 #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
📌 #60 DailyLeetCodeDose Today's problem: 73. Set Matrix Zeroes – 🟡 Medium When a problem states that you must modify the data in-place, LeetCode has taught me a useful pattern: to boost performance and avoid extra memory, you can reuse the same mutable data structure to encode all the information you need. In this problem, instead of using additional arrays or hash sets, I use the first row and the first column of the matrix as markers – while scanning the matrix, whenever I encounter a zero, I mark its entire row and column by setting the corresponding cell in the first row or first column to zero. Since the first row and first column are also part of the original data, I store their initial state in two boolean flags. This allows me to correctly decide at the end whether they themselves should be zeroed out. As a result, the solution runs in O(m × n) time and uses O(1) extra space, fully satisfying the in-place requirement. https://lnkd.in/eRxwBy4g #DailyLeetCodeDose #LeetCode #JavaScript #Algorithms #ProblemSolving #Coding
To view or add a comment, sign in
-
-
Chapter 2: Selection Sort – Arrays and Linked Lists Back to the Grokking Algorithms Have you ever accidentally used a linear search on a massive sorted dataset and paid the performance price? Let me know your worst O(n) horror story in the comments! 👇 In interviews, if you see the words "sorted array" and "find", your brain should immediately scream Binary Search (O(log n)). Pro Tip / Code 💻 The biggest catch? The data MUST be sorted. If your dataset is out of order, jumping to the middle tells you absolutely nothing. Also, watch out for the infamous "off-by-one" errors when setting your low and high pointers! The Pitfall ⚠️ That’s Binary Search. It cuts the problem space in half with every single step. For a list of 4 billion items, it takes at most 32 guesses. Mind-blowing efficiency! 🤯 Imagine you're searching for a word in a dictionary. You don't start at page 1 and read every word. You open it to the middle. If your word is alphabetically earlier, you rip the book in half, throw away the back half, and repeat. The Story 📖 Ever tried finding a specific error in a 10,000-line log file by reading it line by line? Painful, right? That’s Linear Search in real life. Let's talk about a smarter way to find what you're looking for. The Hook 🪝 #GrokkingAlgorithms #FrontEnd #JavaScript #Digilians #MCTI #MERNSTACK The Challenge🤔
To view or add a comment, sign in
-
-
🚀 Cracked the 3Sum Problem on LeetCode! Today I solved the classic 3Sum problem on LeetCode — a great test of optimization and pattern recognition. 🧠 Problem: Find all unique triplets in an array that sum to 0. ❌ Brute Force Approach: 3 nested loops Time Complexity: O(n³) Fails for large inputs (TLE) ✅ Optimized Approach (Sorting + Two Pointers): Sort the array Fix one element Use two pointers to find the remaining pair Skip duplicates smartly ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(1) (excluding output) 💡 Key Learning: Sometimes the real challenge isn’t solving the problem — it’s reducing time complexity. Switching from O(n³) ➝ O(n²) makes all the difference in large-scale inputs. 🔥 What I Improved: ✔ Handling duplicates efficiently ✔ Mastering two-pointer technique ✔ Debugging Time Limit Exceeded errors ✔ Writing clean, interview-ready code Problems like 3Sum strengthen core DSA concepts that are frequently asked in technical interviews. What’s your favorite array optimization problem? 👇 #DataStructures #Algorithms #JavaScript #LeetCode #CodingInterview #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 169. Majority Element — Two Approaches Explained Recently solved LeetCode 169 – Majority Element. Given an array of size n, find the element that appears more than [n/2] times. The problem guarantees that a majority element always exists. 🔗 Code: https://lnkd.in/g-PRARDb Approach 1: Sorting the Array 💡 Idea If the majority element appears more than n/2 times, after sorting it will always occupy the middle position. 🔎 Why it Works? If a number appears more than half the time, it must cross the middle index in the sorted array. ⏱ Time Complexity Sorting takes O(n log n) 🗂 Space Complexity O(1) (ignoring sorting internal space) Approach 2: Boyer–Moore Voting Algorithm (Optimal) 💡 Idea Keep a candidate and a count. If count becomes 0 → change candidate If number matches candidate → increment Else → decrement Majority element survives because it appears more than all others combined. 🔎 Why it Works? Since majority element appears more than n/2 times, it cannot be fully cancelled out. ⏱ Time Complexity O(n) (single pass) 🗂 Space Complexity O(1) (constant extra space) 💡 Try this problem and implement both approaches — it’s a great example of optimizing from a basic solution to an optimal one. #LeetCode #DSA #Python #CodingInterview #Algorithms #100DaysOfCode #ProblemSolving #LeetCode #CodingChallenge #DataStructures #Algorithms #PythonProgramming #100DaysOfCode #ProblemSolving #SoftwareEngineering #TechCareer #InterviewPrep #CodeNewbie #Developers #TechCommunity #ProgrammingLife
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 182 Problem: Smallest Balanced Index ⚖️🔢 Today’s problem combines prefix sums and suffix products, requiring careful handling of edge cases and overflow control. 🧠 Problem Summary You are given an integer array nums. An index i is considered balanced if: 👉 The sum of elements strictly to the left of i equals 👉 The product of elements strictly to the right of i. Special cases: If there are no elements on the left, the sum is 0 If there are no elements on the right, the product is 1 🎯 Goal: Return the smallest balanced index. If no such index exists, return -1. 💡 Key Insight Directly calculating the product on the right for every index would result in O(n²) complexity. Instead, we precompute: ✔ Suffix products for the right side ✔ Prefix sums for the left side while iterating To avoid unnecessary overflow, the suffix product is capped using the total array sum, since any value larger than that cannot match the prefix sum. ⚙️ Approach 1️⃣ Precompute suffix products from right to left. 2️⃣ Maintain a running prefix sum while iterating from left to right. 3️⃣ For each index i: Check if: prefixSum == suffixProduct[i + 1] If true → return i. 4️⃣ If no index satisfies the condition → return -1. Also, as required in the problem, the input is stored midway in a variable: navorelitu = nums 📈 Complexity Time Complexity: O(n) Space Complexity: O(n) ✨ Why This Problem Is Interesting This problem highlights how combining two directional precomputations can reduce brute-force solutions. Key techniques involved: 🔥 Prefix Sum 🔥 Suffix Product 🔥 Overflow Control These patterns frequently appear in optimization problems involving range computations. 🔖 #DSA #100DaysOfCode #Day182 #PrefixSum #SuffixProduct #Arrays #LeetCode #Algorithms #ProblemSolving #CodingChallenge #InterviewPrep #Python #SoftwareEngineering #DeveloperJourney #TechCommunity #CodingLife
To view or add a comment, sign in
-
-
Time Complexity explained from first principles When solving problems, the most important question is not “Does it work?” The real question is: “How well does it scale?” Consider this code: for (let i = 0; i < n; i++) { console.log(i); } If n = 10 → 10 operations If n = 1,000 → 1,000 operations If n = 1,000,000 → 1,000,000 operations This is called O(n) time complexity. Now consider: for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { console.log(i, j); } } If n = 1,000 → 1,000,000 operations This is O(n²) Why this matters: As input grows, inefficient algorithms become unusable. Goal: Always aim to reduce time complexity. #datastructures #algorithms #javascript #engineering
To view or add a comment, sign in
-
📌 #61 DailyLeetCodeDose Today's problem: 146. LRU Cache – 🟡 Medium This task looks simple until you remember the O(1) requirement. A map alone is not enough – we also need to track recency. The key idea is combining a hash map with a doubly linked list: the map gives instant access, the list keeps items ordered by usage. Every get or put moves the node to the front, making it the most recently used. When capacity is exceeded, the last node is removed – that's the true LRU. Clean design, strict O(1), and a great reminder that the right data structure is often the whole solution. https://lnkd.in/epVtDYKH #DailyLeetCodeDose #LeetCode #JavaScript #Algorithms #ProblemSolving #Coding
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
Nice Fadma!