Imagine finding the longest number streak in an unsorted array. For example: [100, 4, 200, 1, 3, 2] Can you spot the longest consecutive sequence? 🚀 Day 67/365 — DSA Challenge Solved: Longest Consecutive Sequence The goal: Find the length of the longest sequence of consecutive numbers. Example: Input [100,4,200,1,3,2] Consecutive sequence: [1,2,3,4] Output: 4 💡 My Approach I solved it in two main steps. Step 1 — Sort the array Since the numbers are unsorted, I first sorted the array using bubble sort. Example after sorting: [1,2,3,4,100,200] Step 2 — Count consecutive numbers Then I looped through the array: • If current number = previous + 1 → increase count • If numbers are equal → skip duplicates • Otherwise → reset count While traversing, I kept track of the longest sequence length. This problem reminded me: Sometimes sorting first makes pattern detection much easier. Day 67/365 complete. Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency
Find Longest Consecutive Sequence in Unsorted Array
More Relevant Posts
-
🔥 Day 353 – Daily DSA Challenge! 🔥 Problem: 🔍 Single Element in a Sorted Array Given a sorted array where every element appears twice except one, find that single element in O(log n) time. 💡 Key Insight — Binary Search on Pairs In a perfect paired array: Pairs start at even indices Pattern breaks at the single element We use binary search to detect where this pattern breaks. 🧠 Core Observation Before the single element: pairs → (even, odd) After the single element: pairs shift → (odd, even) So we normalize mid: if mid is odd → make it even ⚡ Algorithm Logic ✅ Find mid ✅ Make mid even ✅ Compare: If nums[mid] == nums[mid+1] → move right Else → move left This narrows down to the single element. ⚙️ Complexity ✅ Time Complexity: O(log n) ✅ Space Complexity: O(1) 💬 Challenge for you 1️⃣ Why do we force mid to be even? 2️⃣ How would you solve this using XOR in O(n)? 3️⃣ What if elements appear thrice except one? #DSA #Day353 #LeetCode #BinarySearch #Arrays #Optimization #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
🔥 Day 356 – Daily DSA Challenge! 🔥 Problem: ⚡ Max Consecutive Ones III Given a binary array nums and an integer k, return the maximum number of consecutive 1s if you can flip at most k zeros. 💡 Key Insight — Sliding Window We maintain a window where the number of zeros is at most k. Core condition: 🧠 How It Works 🔹 Expand the window using right 🔹 Count zeros in the window 🔹 If zeros exceed k → shrink from left 🔹 At every step, window length is a valid answer ⚡ Algorithm Steps ✅ Initialize: left = 0, zero = 0, max = 0 ✅ Traverse with right: If nums[right] == 0 → increment zero While zero > k: shrink window from left Update max length ⚙️ Complexity ✅ Time Complexity: O(n) (each element processed once) ✅ Space Complexity: O(1) 💬 Challenge for you 1️⃣ Why does this work only for binary arrays? 2️⃣ How would you modify this for longest substring with at most k distinct characters? 3️⃣ What if we want to flip exactly k zeros instead of at most k? #DSA #Day356 #LeetCode #SlidingWindow #TwoPointers #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
🔥 Day 364 – Daily DSA Challenge! 🔥 Problem: 🎯 Find K Closest Elements Given a sorted array arr, an integer k, and a target x, return the k closest elements to x in ascending order. 💡 Key Insight — Binary Search on Window Instead of checking each element, we binary search the starting index of a window of size k. Search space: Possible windows → [0 ... n - k] 🧠 Decision Logic At index mid, compare: Distance of left boundary → x - arr[mid] Distance of right boundary → arr[mid + k] - x We choose direction based on: ⚡ Algorithm Steps ✅ Initialize: left = 0, right = n - k ✅ Binary search: If left side is farther → shift right Else → move left ✅ Final window starts at left ✅ Collect k elements ⚙️ Complexity ✅ Time Complexity: O(log(n - k) + k) (binary search + result building) ✅ Space Complexity: O(k) 💬 Challenge for you 1️⃣ Why do we search on window positions instead of elements? 2️⃣ Can you solve this using a heap approach? 3️⃣ What if array was unsorted? #DSA #Day364 #LeetCode #BinarySearch #SlidingWindow #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
🚀 DSA Preparation 💪 Solved an interesting Array + Sliding Window problem on maximizing score. Instead of picking cards directly, learned to think in reverse by finding the minimum subarray to exclude 🔥 This approach helps in optimizing the solution efficiently 🚀 🧠 Problem 🔎 Maximum Points You Can Obtain from Cards Given an array cardPoints and an integer k, you can take cards from the beginning or end. 👉 You must take exactly k cards. 👉 Return the maximum score possible. Example Input: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12 Input: cardPoints = [2,2,2], k = 2 Output: 4 Input: cardPoints = [9,7,7,9,7,7,9], k = 7 Output: 55 Improving DSA with better thinking and optimization 🚀 #DSA #LeetCode #SlidingWindow #Arrays #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 28 Today’s focus: Binary Search for minimum in rotated arrays. Problem solved: • Find Minimum in Rotated Sorted Array (LeetCode 153) Concepts used: • Binary Search • Identifying unsorted half • Search space reduction Key takeaway: The goal is to find the minimum element in a rotated sorted array. Using binary search, we compare the mid element with the rightmost element: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) This works because the rotation creates one unsorted region, and the minimum always lies in that region. By narrowing the search space each time, we achieve O(log n) time complexity. This problem highlights how slight modifications in array structure still allow binary search to work efficiently with the right observations. Continuing to strengthen binary search patterns and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 10 Today’s focus: Prefix Sum and Sliding Window techniques. Problems solved: • Binary Subarrays With Sum (LeetCode 930) • Maximum Sum of Distinct Subarrays With Length K (LeetCode 2461) Concepts used: • Prefix Sum with HashMap • Sliding Window technique • Frequency tracking for distinct elements Key takeaway: In Binary Subarrays With Sum, the goal is to count the number of subarrays whose sum equals a given target. This can be solved efficiently using the prefix sum technique combined with a HashMap. As we iterate through the array, we keep track of the running sum and check how many times (currentSum - goal) has appeared before. This allows us to count valid subarrays in O(n) time. In Maximum Sum of Distinct Subarrays With Length K, a fixed-size sliding window is used. While moving the window across the array, we maintain a frequency map to ensure all elements in the window are distinct. If the window contains exactly k unique elements, we update the maximum sum. These problems highlight how recognizing the right pattern—prefix sums for counting subarrays and sliding windows for fixed-length constraints—can significantly reduce brute-force complexity. Continuing to strengthen pattern recognition and consistency in solving DSA problems. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day 347 – Daily DSA Challenge! 🔥 Problem: 📈 Non-decreasing Subsequences Given an integer array nums, return all the different non-decreasing subsequences of length ≥ 2. 💡 Key Insight — Bitmask Enumeration Instead of backtracking, we can generate all subsequences using bitmasking. If the array length is n, the total subsets are: Each mask represents a subsequence: Bit 1 → include element Bit 0 → skip element Then we simply filter valid subsequences. 🧠 Validation Step A subsequence is valid if: nums[i] ≥ nums[i-1] for all elements. We also store results in a HashSet to avoid duplicates. ⚡ Algorithm Steps ✅ Generate all subsets using bitmask (0 → 2^n - 1) ✅ Build subsequence from set bits ✅ Check: size ≥ 2 non-decreasing order ✅ Add to Set<List<Integer>> ✅ Convert set to list ⚙️ Complexity ✅ Time Complexity: O(n × 2ⁿ) (all subsets checked) ✅ Space Complexity: O(2ⁿ) 💬 Challenge for you 1️⃣ How would you solve this using backtracking instead of bitmasking? 2️⃣ Why do duplicates appear when numbers repeat? 3️⃣ How can we avoid using a HashSet? #DSA #Day347 #LeetCode #Bitmasking #Subsequences #Backtracking #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
Leveling up my Array manipulation skills today with the Two-Pointer approach! After mastering basic array traversal, it was time to tackle actual problem-solving patterns. Today, I used the Two-Pointer technique to reverse an array entirely in-place. Instead of creating a second array and wasting memory, you use two indices working together: Pointer 1: Starts at the beginning (left = 0). Pointer 2: Starts at the end (right = n- 1). Action: Swap the elements, then move the pointers toward the middle. Stop: When the pointers meet or cross! The beauty of this pattern? It runs in O(n) time and an incredibly efficient O(1) auxiliary space. Learning how to manipulate data without relying on extra memory is a huge shift in how I think about algorithm design. #DSA #Java #TwoPointerApproach
To view or add a comment, sign in
-
-
Most people overcomplicate this problem. I almost did too. 🚀 Day 78/365 — DSA Challenge Find K Closest Elements You're given a sorted array. Pick k elements closest to x. Sounds simple... but there's a catch: You must return them sorted And follow distance rules carefully. 💡 My Approach: Instead of checking every combination... I used a two-pointer shrinking window Start with the full array Then shrink it until only k elements remain At each step: Compare: • distance from start → |arr[start] - x| • distance from end → |arr[end] - x| Remove the one farther from x Repeat until window size = k ⚡ Why this works: We always remove the worst candidate So the remaining window is optimal ⏱ Time: O(n) 📦 Space: O(1) What I learned: Sometimes the solution is not about building... It's about removing smartly Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🔥 Day 346 – Daily DSA Challenge! 🔥 Problem: ⚡ Total Hamming Distance The Hamming distance between two integers is the number of bit positions where they differ. Given an integer array nums, return the sum of Hamming distances between all pairs. 💡 Key Insight — Count Bits Column-wise Instead of comparing every pair (O(n²)), analyze each bit position independently. For a given bit: Let ones = number of elements with that bit = 1 Let zeros = n - ones Each pair of (1,0) contributes 1 to Hamming distance. Total contribution for that bit: Sum this for all 32 bits. For each bit column we count ones × zeros and add them. ⚡ Algorithm ✅ Iterate through 32 bit positions ✅ Count how many numbers have that bit set ✅ Compute contribution ones × (n − ones) ✅ Add to result ⚙️ Complexity ✅ Time Complexity: O(32 × n) ≈ O(n) ✅ Space Complexity: O(1) 💬 Challenge for you 1️⃣ Why does this approach avoid pairwise comparison? 2️⃣ How would this change for 64-bit numbers? 3️⃣ Can this be extended to compute XOR sum of all pairs? #DSA #Day346 #LeetCode #BitManipulation #HammingDistance #Math #Java #ProblemSolving #KeepCoding
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