🔥 Day 35/100 of #100DaysOfCode - Finding Longest Sequence! Today's Problem: Longest Consecutive Sequence Task: Find the length of the longest consecutive elements sequence in an unsorted array. Solution: Used a HashSet for O(1) lookups! First added all elements to the set, then for each number, checked if it's the start of a sequence (no num-1 in set). If yes, counted consecutive numbers ahead. Key Insights: O(n) time complexity by only checking sequence starters HashSet eliminates duplicates and provides fast lookups Avoids O(n log n) sorting approach Smart Optimization: Only begins counting from sequence starting points Each number is processed at most twice (visited in set iteration + sequence counting) Handles duplicates and empty arrays gracefully Elegant solution that transforms an O(n²) brute force into O(n) using smart data structure choice! 💡 #100DaysOfCode #LeetCode #Java #Algorithms #HashSet #Arrays #CodingInterview
Solved Longest Consecutive Sequence with HashSet in Java
More Relevant Posts
-
🚀 Day 28 of #100DaysOfCode Today’s challenge was all about understanding frequency patterns in arrays — a simple yet powerful concept in hashing 🔍 LeetCode 1207 – Unique Number of Occurrences 🔢 📌 Problem Summary: Given an integer array, determine whether each value appears a unique number of times. In other words, 👉 No two numbers should share the same frequency. 💡 Example: Input: [1,2,2,1,1,3] Output: true Because frequencies are: 1 → 3 times 2 → 2 times 3 → 1 time All unique ✔️ 🧠 My Approach: I solved it using a combination of HashMap + HashSet: 1️⃣ Count the occurrences of each number using a HashMap. 2️⃣ Insert all frequency values into a HashSet. 3️⃣ If the size of the HashSet equals the size of the map → all frequencies are unique ✔️ 4️⃣ Otherwise → duplicates exist ❌ A clean and efficient hashing technique. ⚙️ Complexity: Time: O(n) ⏱️ Space: O(n) 💾 (storing frequencies) 💡 Key Learning: HashMaps aren’t just for storing counts—they can reveal patterns, validations, and uniqueness constraints when combined with sets. This problem reinforced how frequency-based logic solves many real-world scenarios like: ✔ Detecting duplicates ✔ Comparing patterns ✔ Character/string analysis ✔ Data validation 🔥 Result: Code ran successfully with 0 ms Runtime, accepted on the first attempt! Small challenge, clean logic, satisfying finish 💪 On to the next one! 🚀 #100DaysOfCode #LeetCode #HashTable #Java #ProblemSolving #DSA #CodingJourney
To view or add a comment, sign in
-
-
💻 Day 63 of #LeetCode100DaysChallenge Solved LeetCode 290: Word Pattern — a great problem for strengthening hash mapping and bijection logic between characters and words. 🧩 Problem: Given a pattern and a string s, determine if s follows the same pattern. Each letter in the pattern maps to exactly one unique word in s, and each unique word in s maps to exactly one letter in the pattern. No two letters map to the same word, and no two words map to the same letter. 💡 Approach — HashMap + Set: 1️⃣ Split s into words. If pattern length ≠ word count, return false. 2️⃣ Use two data structures: A HashMap<Character, String> to map pattern → word. A HashSet<String> to track if a word is already mapped. 3️⃣ Iterate through both: If the character was seen before, check if it maps to the same word. If it’s new, ensure the word isn’t already mapped to another letter. 4️⃣ Return true if all pairs match consistently. ⚙️ Complexity: Time: O(N) — one pass through all words. Space: O(N) — for the map and set. ✨ Key Takeaways: ✅ Strengthened understanding of bijections and hash-based pattern matching. ✅ Improved clarity on how to manage two-way mapping between characters and strings. ✅ Practiced clean iteration and map validation logic — crucial for real-world parsing and pattern-matching problems. #LeetCode #100DaysOfCode #Java #HashMap #PatternMatching #DSA #ProblemSolving #WomenInTech #CodingChallenge
To view or add a comment, sign in
-
-
🚩 Problem: 239. Sliding Window Maximum 🔥 Day 51 of #100DaysOfLeetCode 🔍 Problem Summary: Given an integer array nums and an integer k, return an array containing the maximum value in every sliding window of size k. This is a classic sliding window problem that looks heavy, but with the right data structure, the solution is clean and O(n). 🧠 Intuition: A normal approach checks each window → O(n × k) (too slow). Instead, use a Deque to store indices of useful elements: The deque always keeps elements in decreasing order. The front of the deque is always the maximum of the current window. Remove elements: Outside the current window Smaller than the new incoming element This gives us the maximum in O(1) per window ⇒ total O(n). ⚙️ Performance: ⏱️ Runtime: 28 ms 🚀 💪 Beats: 98.7% of Java solutions 💾 Memory: 63 MB ⚡ (Beats ~96% of users) 📊 Complexity: Time Complexity: O(n) Space Complexity: O(k) ✨ Key Takeaway: The Deque technique is one of the most powerful sliding window optimizations — turning a potentially quadratic problem into linear time with a clean and elegant solution. Link:[https://lnkd.in/gJTzhcR2] #100DaysOfLeetCode #Day51 #Problem239 #SlidingWindowMaximum #Deque #SlidingWindow #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DataStructures #CodingCommunity #ArjunInfoSolution #CodeNewbie #Programming #TechCareers #CareerGrowth #ZeroToHero #LearnToCode #CodingIsFun #ComputerScience #JavaDeveloper #DeveloperJourney #AI #MachineLearning #UnityGameDev #GameDeveloper
To view or add a comment, sign in
-
-
✅ Day 68 of LeetCode Medium/Hard Edition Today’s challenge was “Number of Ways to Form a Target String Given a Dictionary” — a brilliant Dynamic Programming and Combinatorics problem that tests precision in transitions and precomputation logic 🧩⚙️ 📦 Problem: You’re given an array of equal-length strings words and a target string target. You must form target from left to right by picking characters from the columns of words under these rules: 1️⃣ Once you use column k from any word, all columns ≤ k in every word become unusable. 2️⃣ You can use multiple characters from the same word, respecting column progression. Return the number of ways to form target modulo 1e9 + 7. 🔗 Problem Link: https://lnkd.in/gns9CwWa ✅ My Submission: https://lnkd.in/g7bsgZq9 💡 Thought Process: This problem is a clever mix of frequency compression and DP memoization. We precompute a frequency table freq[26][m], where each cell represents how many words contain a given letter at column m. Then, using recursion with memoization: 🎯 At each step (i, j) Either use freq[target[i]][j] if it exists → multiply by ways for the next position (i+1, j+1) Or skip the current column → move to (i, j+1) The recurrence relation: dp[i][j] = freq[target[i]][j] * dp[i+1][j+1] + dp[i][j+1] All computations are done modulo 1e9 + 7. ⚙️ Complexity: ⏱ Time: O(26 * n + t * m) — efficient due to frequency precomputation 💾 Space: O(t * m) — for memoized DP table 💭 Takeaway: This challenge reinforced how precomputation and state optimization can transform a seemingly exponential recursion into an elegant polynomial-time solution 🚀 #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #Combinatorics #ProblemSolving #Java #CodingChallenge #DSA
To view or add a comment, sign in
-
-
🚩 Problem: 56. Merge Intervals 🔥 Day 58 of #100DaysOfLeetCode 🔍 Problem Summary: You are given an array of intervals where each interval is [start, end]. Merge all overlapping intervals and return the result. 🧠 Intuition: This is a classic sorting + merging problem. Steps: Sort intervals based on starting time Traverse them one by one If the current interval overlaps with the previous one, merge them Otherwise, add the current interval as a new block The idea is extremely simple once sorted. 🔑 When do intervals overlap? If: current.start ≤ previous.end → merge Else → start a new interval blockPerformance: ⏱️ Runtime: 6 ms 🚀 💪 Beats: 97.5% of Java solutions 💾 Memory: 45 MB ⚡ (Beats ~93% of users) 📊 Complexity: Time Complexity: O(n log n) (due to sorting) Space Complexity: O(n) (result list) ✨ Key Takeaway: This problem teaches the powerful pattern: Sort → Sweep → Merge It’s used in many real-world applications: CPU scheduling Calendar merging Event time-line processing Data range compression A must-know for top interview rounds. Link:[https://lnkd.in/gCRpSVJW] #100DaysOfLeetCode #Day58 #Problem56 #MergeIntervals #Sorting #GreedyAlgorithms #DSA #Java #ProblemSolving #CodingChallenge #LeetCode #CodingCommunity #InterviewPreparation #CrackingTheCodingInterview #SoftwareEngineering #DeveloperJourney #ArjunInfoSolution #TechCareers #CareerGrowth #DataStructures #Programming #ZeroToHero #CodeNewbie #LearnToCode #CodingIsFun #JavaDeveloper #GameDeveloper #Unity #AI #MachineLearning
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞: 3228. 𝐌𝐚𝐱𝐢𝐦𝐮𝐦 𝐍𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 𝐎𝐩𝐞𝐫𝐚𝐭𝐢𝐨𝐧𝐬 𝐭𝐨 𝐌𝐨𝐯𝐞 𝐎𝐧𝐞𝐬 𝐭𝐨 𝐭𝐡𝐞 𝐄𝐧𝐝 This problem was a solid blend of string traversal, pattern observation, and counting logic. It highlights how understanding movement constraints in binary strings can simplify what initially looks like a simulation-heavy problem. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: We are given a binary string. In one operation, we can select a '1' that is immediately followed by a '0' and push that '1' as far right as possible until it hits another '1' or the end of the string. The goal is to compute the maximum number of such operations. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Instead of simulating each movement, the key insight was to understand when a movement is allowed. Traverse the string and count how many '1's have appeared so far. Every time we encounter a '0' after some '1's, it contributes operations equal to the number of '1's on its left. This avoids unnecessary swaps and keeps the solution optimal. The entire logic comes down to: Count continuous '1's. Add that count whenever a movable '0' appears. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n) Space Complexity: O(1) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬: Pattern-based counting can completely eliminate simulation-heavy logic. Movement-based problems often reduce to understanding relative ordering rather than performing every shift. A single-pass solution can emerge when you carefully track what each character contributes. This challenge strengthened my ability to break down string movement problems into pure counting logic rather than brute operations. #LeetCode #DSA #Java #ProblemSolving #CodingPractice #Algorithms #LearningJourney #Consistency
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞: 1513. 𝐍𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 𝐒𝐮𝐛𝐬𝐭𝐫𝐢𝐧𝐠𝐬 𝐖𝐢𝐭𝐡 𝐎𝐧𝐥𝐲 1𝐬 Today’s problem was a clean exercise in mathematical pattern recognition within strings — proving that sometimes, counting smartly beats looping endlessly. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: We are given a binary string and need to count the number of substrings consisting entirely of '1's. Since the count can be large, the result is returned modulo 10⁹ + 7. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: The core insight is recognizing how consecutive '1's form substrings: For a group of k consecutive '1's, the number of valid substrings = k * (k + 1) / 2. Instead of explicitly using this formula, I used a simple iterative approach: Keep a running counter for consecutive '1's. Add that counter to the result whenever we encounter another '1'. Reset the counter on a '0'. This yields an elegant O(n) single-pass solution with constant space. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n) Space Complexity: O(1) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬: Mathematical series reasoning helps simplify substring problems. Consecutive counting avoids redundant substring generation. Simplicity and pattern recognition often lead to the most optimal logic. A great reminder that not every problem needs complexity — sometimes, it’s all about spotting the sequence. #LeetCode #DSA #Java #ProblemSolving #Algorithms #CodingPractice #LearningJourney #100DaysOfCode #Consistency #BinaryStrings
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #654 — Maximum Binary Tree 📘 Problem: Given an integer array without duplicates, the task is to build a maximum binary tree. The construction rules are: 1️⃣ The root is the maximum element in the array. 2️⃣ The left subtree is built recursively from elements to the left of the maximum. 3️⃣ The right subtree is built recursively from elements to the right of the maximum. Example: Input → [3,2,1,6,0,5] Output → [6,3,5,null,2,0,null,null,1] 🧠 My Approach: I solved this problem using a recursive divide-and-conquer approach. 1️⃣ Find the index of the maximum element in the given range — this becomes the root. 2️⃣ Recursively build the left subtree from the subarray before the maximum element. 3️⃣ Recursively build the right subtree from the subarray after the maximum element. 💡 What I Learned: ✅ How recursion naturally fits into tree construction problems ✅ The concept of divide and conquer applied to array-based tree building ✅ How to translate problem definitions into direct recursive structure #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
🚩 Problem: 169. Majority Element 🔥 Day 43 of #100DaysOfLeetCode 🔍 Problem Summary: Given an array nums, find the element that appears more than ⌊ n/2 ⌋ times. You may assume that the majority element always exists in the array. ✅ Approach 1: Using HashMap Count the frequency of each element using a HashMap and return the one that occurs most frequently. ✅ Approach 2 (Optimized): Boyer–Moore Voting Algorithm Maintain a candidate and count. Traverse the array: If count == 0, set candidate = num. If num == candidate, increment count, else decrement. Return the candidate. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ✨ Key Takeaway: The Boyer–Moore Voting Algorithm is a brilliant example of how a deep understanding of problem constraints can lead to an O(1) space solution — an essential pattern in algorithmic thinking. Link:[https://lnkd.in/gsc4XgbK] #100DaysOfLeetCode #Day43 #Problem169 #MajorityElement #BoyerMoore #Algorithms #DSA #Java #CodingChallenge #ProblemSolving #LeetCode #InterviewPreparation #DataStructures #TechCareers #ArjunInfoSolution #CodingCommunity #CodeNewbie #SoftwareEngineering #ZeroToHero #LearnToCode
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 66 String Manipulation & Primitive Decomposition 🧩 Task: Given a valid parentheses string, decompose it into its primitive components and then remove the outermost parentheses from each component. Example: Input: s = "(()())(())" Primitive Decomposition: "(()())" + "(())" After removing outermost parentheses: "()()" + "()" Output: "()()()" My Approach: I iterated through the string while keeping a counter to track the balance of open parentheses. When an opening parenthesis ( was found, I incremented the counter. If the count was greater than 1, it meant this parenthesis was not an outermost one, so I appended it to the result. When a closing parenthesis ) was found, I only appended it if the counter was greater than 1 before decrementing. This ensures the final closing parenthesis of a primitive part is excluded. This simple counter-based approach effectively identifies and removes the correct parentheses without needing a more complex data structure like a stack. Time Complexity: O(N) Space Complexity: O(N) Sometimes, a simple counter is all you need to elegantly handle nested structures. It can be a clean and efficient alternative to more complex data structures for certain problems. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #DataStructures #Algorithms #StringManipulation #CodeNewbie
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