🚀 Day 94 of My 100 Days LeetCode Challenge | Java Today’s problem was more about data structure design and mathematical optimization than just writing loops. The challenge was to design a Fancy sequence that supports the following operations efficiently: • Append a value • Add a number to all elements • Multiply all elements by a number • Retrieve an element at a specific index At first glance, updating every element after each operation seems straightforward — but that would be too slow. The key insight was to avoid updating all elements directly and instead track the transformations using lazy math operations (multiplication and addition factors) with modular arithmetic. By maintaining global add and multiply factors, we can apply transformations mathematically and compute the actual value only when needed. ✅ Problem Solved: Fancy Sequence ✔️ All test cases passed (107/107) ⏱️ Runtime: 45 ms 🧠 Approach: Data Structure Design + Modular Arithmetic + Lazy Updates 🧩 Key Learnings: ● Sometimes the best solution is avoiding unnecessary updates. ● Lazy evaluation can drastically improve performance. ● Modular arithmetic is essential when dealing with large numbers. ● Mathematical transformations can simulate bulk operations efficiently. ● Designing scalable data structures requires thinking beyond direct computation. This problem felt closer to real-world system optimization, where efficiency comes from smart design rather than brute-force updates. 🔥 Day 94 complete — improving my data structure design thinking and mathematical optimization skills. #LeetCode #100DaysOfCode #Java #DataStructures #Algorithms #ProblemSolving #DSA #CodingJourney #Consistency
Designing Efficient Data Structures with Modular Arithmetic
More Relevant Posts
-
🚀 **LeetCode Problem Solved – Max Consecutive Ones III** Today I solved **Problem 1004: Max Consecutive Ones III** using the **Sliding Window technique**. 🔹 **Problem Summary** Given a binary array `nums` containing 0s and 1s and an integer `k`, we are allowed to flip at most `k` zeros to ones. The goal is to determine the **maximum number of consecutive 1s** possible after performing at most `k` flips. 🔹 **Approach** Instead of checking every possible subarray, I used the **Sliding Window (Two Pointer) approach**: • Expand the window using the right pointer • Count the number of zeros in the window • If zeros exceed `k`, move the left pointer to maintain a valid window • Track the maximum window size 🔹 **Complexity** ⏱ Time Complexity: **O(n)** 💾 Space Complexity: **O(1)** 📊 **Result** ✔ 60 / 60 Testcases Passed ⚡ Runtime: **2 ms (Beats 99.93%)** Consistent practice with **Data Structures & Algorithms** helps build strong problem-solving skills and deeper understanding of algorithmic patterns. Always open to learning better approaches or optimizations! 💡 #LeetCode #DSA #Java #SlidingWindow #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 DAY 73/150 — STARTING MY BINARY TREE JOURNEY! 🌳 Day 73 of my 150 Days DSA Challenge in Java and today I stepped into a new data structure: Binary Trees 💻🧠 Binary Trees are fundamental for many advanced topics like BST, Heaps, Graphs, and recursion-based problems. Starting this journey feels like unlocking a whole new level in DSA 🚀 📌 Problem Solved: Count Complete Tree Nodes 📌 LeetCode: #222 📌 Difficulty: Easy-Medium The task is to count the total number of nodes in a complete binary tree efficiently. A complete binary tree is a tree where: • All levels are completely filled except possibly the last • The last level is filled from left to right 🔹 Approach Used Instead of traversing all nodes (O(n)), I used an optimized approach: • Calculate the height of left subtree and right subtree • If both heights are equal → left subtree is perfect • Else → right subtree is perfect Using this observation, we can calculate nodes using the formula: 👉 2^h - 1 for perfect trees This reduces unnecessary traversal. ⏱ Complexity Time Complexity: O(N) Space Complexity: O(H) (height of a tree) 🧠 What I Learned • Binary Trees require recursive thinking and structural understanding • Recognizing special tree properties (like complete trees) helps optimize solutions • Not every tree problem requires full traversal 💡 Key Takeaway This problem taught me how mathematical observations + tree properties can significantly reduce time complexity. Starting my Binary Tree journey will help me explore: Tree traversals (DFS, BFS) Recursion patterns Advanced structures like BST and heaps ✅ Day 73 completed 🚀 77 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gCnGSuQc 💡 Trees are where recursion truly comes to life. #DSAChallenge #Java #LeetCode #BinaryTree #Recursion #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
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 19 of Consistency – Optimized “Intersection of Two Arrays II” (LeetCode) Today I pushed one step further and solved a variation where duplicates also matter — making it slightly more challenging and interesting. 🔍 Problem Understanding Given two arrays, return their intersection including duplicates. Each element should appear as many times as it shows in both arrays. 🧠 Initial Thought (Brute Force) Compare each element of one array with another Track used elements manually ⛔ Inefficient due to nested loops → O(n × m) ⚡ Optimized Approach (HashMap – Frequency Count) 👉 This time, I used a smarter strategy: Store frequency of elements from nums1 in a HashMap Traverse nums2 If element exists in map and count > 0: Add to result Decrease frequency 💡 Example nums1 = [1,2,2,1] nums2 = [2,2] Output → [2,2] ⏱ Complexity Analysis Time Complexity: O(n + m) Space Complexity: O(n) 📊 Result ✔️ All test cases passed (61/61) ⚡ Runtime: 3 ms 🔥 Beats 95.42% submissions 🧩 Key Learning HashMap is extremely useful for frequency-based problems Handling duplicates = tracking counts properly Small optimization can drastically improve performance 🙏 Grateful for the journey and learning every single day 🔥 Consistency + Optimization = Growth mindset #DSA #Java #LeetCode #CodingJourney #HashMap #ProblemSolving #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 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
To view or add a comment, sign in
-
-
Day #10 / 100 — Data Structures & Algorithms Today’s focus was on array patterns and two-pointer techniques. Problems solved: • Maximum Subarray • Container With Most Water • Minimum Size Subarray Sum • Longest Substring Without Repeating Characters • 4Sum • Maximum Width Ramp • Boats to Save People Key takeaway: Many array problems reduce to a few core ideas — sliding window, two pointers, greedy choices, or prefix-based reasoning. Recognizing these patterns is gradually making problem-solving faster and more intuitive. #100DaysOfCode #DSA #LeetCode #Java #BackendDevelopment AccioJob
To view or add a comment, sign in
-
-
🚀 100 Days of Code Day-25 LeetCode Problem Solved: Reverse Nodes in k-Group I recently worked on a Linked List problem that focuses on reversing nodes in groups of size k while preserving the remaining structure if the group size is less than k. 🔹 Strengthened my understanding of pointer manipulation 🔹 Improved problem decomposition skills 🔹 Practiced recursive thinking for efficient implementation 💡 Key takeaway: Breaking complex problems into smaller, manageable parts significantly simplifies the solution approach. Continuing to build consistency in problem-solving and deepen my understanding of Data Structures & Algorithms. #LeetCode #DataStructures #Algorithms #Java #ProblemSolving #SoftwareDevelopment
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
-
-
HI CONNECTIONS I recently tackled LeetCode 166, a problem that requires careful handling of edge cases, integer overflows, and the logic of long division. 🔍 The Challenge Given two integers representing a fraction, return the result in string format. If the fractional part repeats, enclose the repeating digit(s) in parentheses. Example: 1 / 2 = 0.5 The Twist: 2 / 3 = 0.(6) 🛠️ My Approach: Long Division with Memory The key to identifying a repeating decimal is realizing that if you encounter the same remainder twice during the division process, the digits will start to repeat from that point onward. Handle Signs & Edge Cases: Determine the sign of the result and handle the case where the numerator is 0. Use long (in Java/C++) to prevent overflow when taking absolute values (e.g., -2147483648). Integer Part: Calculate the whole number part using numerator / denominator. Fractional Part: * Use a Hash Map to store each remainder and its corresponding index in the result string. Multiply the remainder by 10 and continue the division. The Detection: If the remainder is already in the map, insert ( at the stored index and ) at the end of the string, then break. Terminate: If the remainder becomes 0, the decimal is terminating. 📊 Efficiency Time Complexity: O(\text{Denominator}) — In the worst case, the number of digits in the repeating part is less than the denominator. Space Complexity: O(\text{Denominator}) — To store the remainders in the hash map. 💡 Key Takeaway This problem is a great reminder that data structures like Hash Maps aren't just for searching—they are essential for "remembering" states in a process. Recognizing cycles is a fundamental skill in both algorithm design and system monitoring. #LeetCode #AlgorithmDesign #HashMaps #Mathematics #SoftwareEngineering #ProblemSolving
To view or add a comment, sign in
-
-
Day 23/100 of DSA , (Arrays) 🚀 Today IPractice – Container With Most Water Solved the classic Two Pointer problem “Container With Most Water” on LeetCode today. I used brute force approach with O(n²) complexity, the problem can be optimized using the Two Pointer technique, reducing the time complexity to O(n). 🔹 Key Idea: Start with two pointers at both ends of the array. Calculate the area using min(height[left], height[right]) * width. Move the pointer with the smaller height to potentially find a taller boundary and maximize the area. 💻 Tech Stack: Java | DSA Consistency in practicing data structures and algorithms is the key to improving problem-solving ability. #DSA #Java #LeetCode #ProblemSolving #CodingJourney #SoftwareDevelopment
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