🗓 Day 59 / 100 – #100DaysOfLeetCode 📌 Problem 961: N-Repeated Element in Size 2N Array Today’s problem focused on identifying a repeating pattern in an array with well-defined constraints. The task was to find the element that appears n times in an array of size 2n, where all other elements are unique. 🧠 My Approach: I used a set-based approach to track elements as I traversed the array: Iterated through each element in the array. Stored visited elements in a set. If an element was already present in the set, that meant it was the repeated element → returned it immediately. This works efficiently because the problem guarantees exactly one element is repeated n times. 💡 Why this works well: Sets provide O(1) average time complexity for lookup. The repeated element is guaranteed to appear early due to frequency, so we can exit early. Simple logic with clean and readable code. 💡 Key Learning: This problem reinforced: ✔ how problem constraints can simplify the solution ✔ effective use of hash-based data structures ✔ recognizing patterns instead of overcomplicating logic ✔ writing efficient solutions even for “easy” problems A great example of how understanding constraints leads to elegant solutions 🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #Arrays #HashSet #Simulation #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
100 Days of LeetCode: N-Repeated Element in Size 2N Array
More Relevant Posts
-
🗓 Day 60 / 100 – #100DaysOfLeetCode 📌 Problem 1411: Number of Ways to Paint N × 3 Grid Today’s problem was a really good exercise in dynamic programming and pattern observation. The goal was to count the number of valid ways to paint an n × 3 grid using three colors, such that no two adjacent cells (horizontal or vertical) share the same color. 🧠 My Approach: Instead of tracking every possible coloring explicitly, I categorized each row into two patterns: 1️⃣ same – Rows where the 1st and 3rd cells have the same color (e.g., A B A) 2️⃣ diff – Rows where all three cells have different colors (e.g., A B C) For the first row: same = 6 diff = 6 Then for each subsequent row: A same pattern can be formed from: previous same rows in 3 ways previous diff rows in 2 ways A diff pattern can be formed from: previous same rows in 2 ways previous diff rows in 2 ways Using these transitions, I iterated row by row and applied modulo 10^9 + 7 to handle large values efficiently. 💡 Key Learning: This problem reinforced: ✔ breaking complex constraints into manageable states ✔ recognizing repeating patterns to optimize DP solutions ✔ reducing a large state space into just a few variables ✔ how mathematical transitions can drastically simplify implementation A perfect example of how thinking in patterns turns a hard-looking problem into a clean and elegant solution 🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #DynamicProgramming #DP #Combinatorics #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
To view or add a comment, sign in
-
-
🗓 Day 64 / 100 – #100DaysOfLeetCode 📌 Problem 1339: Maximum Product of Splitted Binary Tree Today’s problem combined tree traversal with optimization logic. The task was to split a binary tree into two subtrees by removing exactly one edge, such that the product of the sums of the two resulting subtrees is maximized. 🧠 My Approach: First, computed the total sum of all nodes in the tree. Used a post-order DFS traversal to calculate the sum of each subtree. For every subtree: Considered it as one part after the split. The other part would have sum: total_sum − subtree_sum Calculated the product of these two values. Tracked the maximum product across all possible splits. Returned the result modulo 109+710^9 + 7109+7, as required. Post-order traversal works perfectly here because subtree sums must be known before evaluating the split. 💡 Key Learning: This problem reinforced: ✔ how post-order DFS is ideal for subtree-based calculations ✔ combining traversal with optimization criteria ✔ thinking globally (total sum) while evaluating local decisions (each split) A great example of how tree problems often require two passes: one for data collection and one for optimization. Another strong tree-based DP-style problem completed 🌳🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #BinaryTree #DFS #TreeDP #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge – Day 4 Problem #1390: Four Divisors (Medium) Today’s problem was one of those that really tested my patience and understanding of time complexity. 🧭 How I Approached the Question: I initially started with a brute-force approach, checking all numbers from 1 to n to find divisors. While this worked for small cases, it quickly became inefficient and failed on larger inputs. I then optimized by: Iterating only up to √n Counting divisors in pairs Breaking early once the divisor count exceeded 4 The key learning moment was realizing that: 👉 A number can have exactly four divisors only when it fits specific mathematical patterns, and we don’t need to enumerate all divisors. Using this insight, I avoided unnecessary loops, skipped perfect squares, and stopped as soon as extra divisors were found — which finally passed all test cases. ⏱ Time Complexity: O(n√k) (with early exits) 📦 Space Complexity: O(1) This problem reinforced an important lesson: 👉 Brute force helps you start, but optimization and math help you finish. 📌 Stay tuned for more daily problem-solving insights and honest coding learnings! #LeetCode #DailyCoding #DataStructures #Algorithms #ProblemSolving #Python #DSA #CodingJourney #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
-
🗓 Day 66 / 100 – #100DaysOfLeetCode 📌 Problem 865: Smallest Subtree with All the Deepest Nodes Today’s problem focused on binary tree depth analysis. The goal was to find the smallest subtree that contains all the deepest nodes in the tree. 🧠 My Approach: Used Depth-First Search (DFS) to compute information bottom-up. For each node, tracked: the maximum depth reachable from that node, and the candidate subtree root that contains all deepest nodes. Compared depths of left and right subtrees: If both sides have the same depth → the current node is the answer. Otherwise, propagated the deeper side upward. Returned the node that satisfies the condition for all deepest nodes. This approach cleanly combines depth calculation with subtree selection in a single traversal. 💡 Key Learning: This problem reinforced: ✔ how returning multiple values from DFS simplifies logic ✔ thinking bottom-up for tree optimization problems ✔ identifying the exact node where depths converge Tree problems often become elegant once the right recursive structure is identified 🌳🚀 #100DaysOfLeetCode #LeetCodeChallenge #Python #ProblemSolving #BinaryTree #DFS #TreeTraversal #Algorithms #DSA #CompetitiveProgramming #SoftwareEngineering #CodingJourney #DeveloperJourney #LearningInPublic #TechStudent #CareerGrowth #Programming #KeepLearning
To view or add a comment, sign in
-
-
🧠 LeetCode Insight — Minimum Window Substring Lately, I’ve been focusing on strengthening my core problem-solving fundamentals, especially patterns that show up repeatedly in real-world engineering problems. One such problem is Minimum Window Substring, which combines: sliding window frequency tracking and careful state management 💡 Core Logic The goal isn’t just to find a valid window — it’s to find the smallest valid window. To do that efficiently: Track required character counts using a frequency map Maintain a dynamic window over the string Expand the window to satisfy constraints Shrink it only when validity is preserved The balance between correctness and optimality is what makes this problem interesting. ✅ Python Implementation: https://lnkd.in/gN-93eB8 🧩 Why This Matters Problems like this test more than syntax — they test: how you manage state how you reason about constraints how you optimize without breaking correctness These are the same skills required when working on scalable backend systems and data pipelines. 🎯 Takeaway The biggest learning for me here was: Sliding window problems aren’t about moving pointers — they’re about knowing exactly when a condition becomes true and when it breaks. Getting that right is what leads to clean, reliable solutions. 👉 Curious how others reason about shrinking windows — what’s your mental model for this pattern? #Python #ProblemSolving #SlidingWindow #DataStructures #SoftwareEngineering #LeetCode #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 53 of #100DaysOfCode — Making Array Sum Divisible by K Hey everyone! 👋 Today’s challenge focused on a smart math-based optimization problem where the goal was to make the sum of an array divisible by a given number k using the minimum number of operations. 👨💻 What I practiced today: ✅ Understanding modulo (%) operations deeply ✅ Translating a problem into a simple mathematical observation ✅ Optimizing brute-force thinking into an O(n) solution ✅ Writing clean and minimal Python code 📌 Today’s Task: ✔ Given an integer array nums and an integer k ✔ In one operation, decrement any element by 1 ✔ Find the minimum operations required so that sum(nums) is divisible by k 🧠 Key Insight: If the sum of the array is S, then the minimum number of operations required is simply: S % k Because each operation reduces the sum by 1. 💡 Example: Input: nums = [3, 9, 7], k = 5 Sum = 19 → 19 % 5 = 4 Output: 4 ✨ Key Takeaway: Sometimes the best solution isn’t complex logic or loops — it’s recognizing a simple mathematical pattern. Mastering such observations can drastically reduce code complexity and runtime. #100DaysOfCode #Day53 #Python #LeetCode #ProblemSolving #MathInProgramming #CodingJourney #DSA #CleanCode
To view or add a comment, sign in
-
-
🚀 LeetCode + DSA — Day 20 Today I solved LeetCode 75: Sort Colors, a classic problem that strengthens in-place sorting and comparison-based logic. 🔹 Problem Overview You’re given an array containing only 0, 1, and 2, representing three different colors. The task is to sort the array in-place so that elements of the same color are adjacent and ordered as 0 → 1 → 2, without using the built-in sort function. 🔹 Approach Used ✔ Used a comparison-based in-place sorting strategy ✔ Iterated through the array and tracked the smallest element index ✔ Swapped elements to position them correctly ✔ Ensured no extra space was used 🔹 Why This Works In-place swapping avoids additional memory usage Controlled iteration guarantees correct ordering Simple logic, yet fully compliant with problem constraints 📊 Performance ✅ All test cases passed ⚡ Runtime: 0 ms (Beats 100%) 💾 Memory: Efficient in-place solution 💡 Key Takeaway Problems with strict constraints push you to think beyond library functions. Mastering in-place operations builds strong fundamentals for real-world systems where space efficiency matters. Consistent practice > complex solutions 💪 #LeetCode #DSA #Python #Arrays #Sorting #InPlaceAlgorithm #ProblemSolving #DailyCoding #CodingPractice #SoftwareDeveloperJourney #LearningByDoing
To view or add a comment, sign in
-
-
🧠 LEETCODE CONSISTENCY SERIES 🚀 Day 1️⃣2️⃣ of 365 Days 🔁 📘 Topic: Number Problem 🧩 Problem: 3Sum (LeetCode #15) ⏱ Time Taken: ~65 minutes 💡 Key Idea: Sort the array first, then fix one element and use the two-pointer technique to find pairs that sum to the negative of the fixed element. Fix nums[i] Use left and right pointers to search for nums[left] + nums[right] = -nums[i] Move pointers based on sum comparison 🛠 Important Techniques Used: Sorting to simplify duplicate handling Two-pointer approach for optimized searching Skipping duplicates to ensure unique triplets only ⚠ Edge Cases Handled: Duplicate values in input array Arrays with less than 3 elements All zero case → [0,0,0] No valid triplet case → return empty list 🚀 What I learned today: How sorting enables efficient two-pointer traversal Proper duplicate removal at both index and pointer levels Reducing brute-force O(n³) to optimized O(n²) 📌 Next Goal: Solve 4Sum using similar logic Practice more problems on two pointers & hashing Consistency > Motivation 💪 🔗 GitHub: https://lnkd.in/dRGB_B8Z #DSA #LeetCode #Python #ProblemSolving #365DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
Day 10/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 844 – Backspace String Compare (Easy) 🧠 Approach: Simulate typing using stacks and compare final strings. 💻 Solution: class Solution: def build(self, s): stack = [] for i in s: if i=="#": if stack: stack.pop() else: stack.append(i) return stack def backspaceCompare(self, s: str, t: str) -> bool: return self . build(s)==self . build(t) ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Stack-based simulation is an effective way to model real-time text editing behavior. #leetcode #dsa #python #stack #codingchallenge
To view or add a comment, sign in
-
-
Day 11 of Python: Mastering Deeply Nested Logic & Real-World Simulations 🧠💻 Today marks a significant step up in my Python Series. I’ve transitioned from simple decision-making to building highly complex, multi-layered systems that simulate real-world administrative and personal scenarios. What I built today: Attendance Eligibility System 🎓: This project calculates attendance percentages and uses nested logic to determine exam eligibility. It handles exceptions by verifying medical certificates and even checking for "Signed and Stamped" documentation through multiple layers of if-elif-else. The AI-Inspired Event Planner 🎭: A deeply nested program that suggests weekend activities based on four dimensions: Mood, Budget, Weather, and Company. It demonstrates how code can branch out into dozens of unique outcomes based on specific user scenarios. Technical Skills Level-Up: Logical Precision: Managing up to 4 levels of nested if statements without breaking the code flow. Input Sanitization: Using .lower() to ensure user input doesn't cause errors. Mathematical Integration: Combining percentage calculations with logical branching. Every line of code I write under the guidance of sir Muhammad Rafay Shaikh is making my logic sharper. Pushing these projects to GitHub feels like building a real portfolio, one day at a time. YouExcel Training Muhammad Rafay Shaikh Follow my journey: 📂 GitHub: https://lnkd.in/dUf-DJ-w #Python #Day11 #LogicBuilding #YouExcel #MuhammadRafayShaikh #NestedLogic #EventPlanner #AttendanceSystem #WomenInTech
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