🚀 Day 45 of #100DaysOfCode – Striver’s DSA Sheet 🚀 ✅ Topic Covered Today: Implement Queue Using Array 💡 Lesson of the Day (Approach-Focused): 🔹 Understanding the Core Idea A queue follows FIFO (First In, First Out) order. Using an array, we simulate this behavior by maintaining: front pointer (f) → points to the first element rear pointer (r) → points to the last inserted element size / capacity → fixed array length 🔹 1️⃣ Enqueue (Insert) Check if queue is full → rear == size - 1 Increment rear Insert element at arr[rear] 🧮 Time Complexity: O(1) 💾 Space Complexity: O(1) extra 🔹 2️⃣ Dequeue (Remove) Check if queue is empty → front == -1 Return element at arr[front] Move front forward If queue becomes empty again → reset front = rear = -1 🧮 Time Complexity: O(1) 🔹 3️⃣ Peek Return arr[front] without removing it. 🧮 Time Complexity: O(1) 🔹 4️⃣ isEmpty / isFull isEmpty: front == -1 isFull: rear == size - 1 ✨ Key Idea: Implementing a queue using an array helps understand pointer movement, memory management, and why sometimes a circular queue is needed when fixed arrays cause unused space. 💭 Learning: Today strengthened my understanding of how queues work under the hood and how core operations actually use pointer updates — a great foundation before moving to circular queues and deque structures. #100DaysOfCode #DSA #StriversSheet #Java #Queue #Arrays #ProblemSolving #CodingJourney #LogicBuilding #Consistency
Implementing Queue Using Array in 100 Days of Code
More Relevant Posts
-
🚀 Day 46 of #100DaysOfCode – Striver’s DSA Sheet 🚀 ✅ Topic Covered Today: Implement Queue Using Linked List 💡 Lesson of the Day (Approach-Focused): 🔹 Understanding the Core Idea A queue follows FIFO (First In, First Out) order. Using a Linked List, we maintain dynamic memory and perform operations efficiently with two pointers: front → points to the first node rear → points to the last node This avoids the limitations of fixed-size arrays. 🔹 1️⃣ Enqueue (Insert at Rear) Approach: Create a new node If queue is empty → front = rear = newNode Else → attach newNode at rear.next and move rear forward 🧮 Time Complexity: O(1) 💾 Space Complexity: O(1) extra 🔹 2️⃣ Dequeue (Remove from Front) Approach: If empty → nothing to remove Return node at front Move front = front.next If queue becomes empty → rear = null 🧮 Time Complexity: O(1) 🔹 3️⃣ Peek Return front.data without removing it. 🧮 Time Complexity: O(1) 🔹 4️⃣ isEmpty Check: front == null 🧮 Time Complexity: O(1) ✨ Key Idea: A linked-list-based queue never overflows (unless memory is full) and supports constant-time insertions and deletions — perfect for dynamic data scenarios. 💭 Learning: Today’s implementation strengthened my understanding of pointers and dynamic memory. Building a queue with linked nodes is a great way to visualize how real queue structures work behind the scenes. #100DaysOfCode #DSA #StriversSheet #Java #LinkedList #Queue #ProblemSolving #CodingJourney #LogicBuilding #Consistency
To view or add a comment, sign in
-
-
🔥 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
To view or add a comment, sign in
-
-
Problem: "73. Set Matrix Zeroes" The core of this problem is simple: if a cell is zero, its entire row and column must become zero. But the execution is tricky—you can't modify the matrix while you're still scanning for original zeros! My solution uses a clean, two-pass strategy with auxiliary storage: Pass 1: Use two HashSets to record the indices of rows and columns that contain an initial zero. Pass 2: Iterate again and set any cell to zero if its row or column is present in the HashSets. This approach is highly readable and ensures optimal O(M . N) time complexity. While this solution uses O(M+N) extra space, it's a fantastic baseline. The next step is tackling the O(1) space constraint by cleverly using the matrix's first row and column as the marker sets. That's the real optimization puzzle! #Algorithms #DataStructures #LeetCode #CodingChallenge #Java #SoftwareEngineering #100daysofcode
To view or add a comment, sign in
-
-
🔥 Day 36/100 of #100DaysOfCode - Matrix Zero Transformation! Today's Problem: Set Matrix Zeroes Task: Given an m x n matrix, if an element is 0, set its entire row and column to 0s. Must be done in-place. Solution: Used the optimal O(1) space approach! Leveraged the first row and first column as markers to track which rows/columns need to be zeroed, with a separate variable for column 0. Key Steps: Mark zeros in first row/column while preserving original state Process inner matrix using the markers Zero rows/columns based on markers Smart Optimizations: Uses matrix itself for storage instead of extra O(m+n) space Handles edge case for first column separately Single pass for marking + two passes for execution Advanced matrix manipulation that demonstrates deep understanding of in-place algorithms! Perfect example of trading complexity for optimal space usage. 🧩 #100DaysOfCode #LeetCode #Java #Algorithms #Matrix #InPlace #CodingInterview
To view or add a comment, sign in
-
-
🔥 Day 121 of My DSA Challenge – Remove Duplicates from Sorted List 🔷 Problem : 83. Remove Duplicates from Sorted List 🔷 Goal : Given the head of a sorted linked list, remove all duplicate nodes so that each element appears only once, while maintaining the sorted order. 🔷 Key Insight : This problem is a great example of linked list traversal and pointer management. Because the list is already sorted, all duplicates appear consecutively — which makes it easy to detect and skip them in one pass. The challenge is to handle links carefully so that only unique nodes remain connected. 🔷 Approach : 1️⃣ Initialize a dummy node (with a distinct value) to simplify linking. 2️⃣ Use a tail pointer to build a new list containing only unique elements. 3️⃣ Traverse the list using head: If head.val is not equal to the last added node (tail.val), link it. Otherwise, skip the duplicate. 4️⃣ Update tail.next = null at the end to avoid leftover links. 5️⃣ Return dummy.next as the new head. Time Complexity: O(n) Space Complexity: O(1) This problem strengthens concepts of : ✅ Duplicate handling in linked lists ✅ Pointer-based traversal ✅ Clean in-place modification Sometimes, cleaning a data structure is just about connecting only what truly matters. ⚡ Every small pattern makes a big difference in problem-solving clarity. One more concept locked in 💻 #Day121 #DSA #100DaysOfCode #LeetCode #Java #LinkedList #ProblemSolving #Algorithms #DataStructures #CodingChallenge #DeveloperJourney #EngineerMindset #GrowEveryday
To view or add a comment, sign in
-
-
🌟 Day 39 of #100DaysOfCode 🌟 🔍 Exploring String Simplification — Removing Duplicates with Precision 🔹 What I Solved Today’s challenge was about simplifying strings by repeatedly removing adjacent duplicate characters until no more exist. A great exercise in stack logic and string manipulation efficiency — proving that small, precise steps can clean up even the messiest data. 🧩 Problem: Remove All Adjacent Duplicates in String 💡 Problem Statement Given a string s, repeatedly remove two adjacent equal letters until none remain. Return the final string after all such duplicate removals. 💡 Example 1: Input: "abbaca" → Output: "ca" Explanation: Remove "bb" → "aaca" → remove "aa" → "ca" 💡 Example 2: Input: "azxxzy" → Output: "ay" 🧠 Concepts Used Stack-based String Processing Iteration & Character Comparison Optimized Linear Solution → O(n) Time, O(n) Space ⚙️ Approach 1️⃣ Use a StringBuilder as a stack. 2️⃣ Traverse each character: • If the current char equals the top of the stack → pop it. • Else → push it. 3️⃣ Return the resulting string from the stack. 🚀 What I Learned ✨ Stack patterns shine even in string problems. ✨ Clean, efficient logic leads to readable and reliable solutions. ✨ Removing redundancy — in code or mindset — leads to clarity. 💬 Reflection Today’s lesson reminded me that refining logic is just like refining thoughts — remove the noise, and the solution becomes clear. #100DaysOfCode #Day39 #StringManipulation #RemoveDuplicates #Java #CodingJourney
To view or add a comment, sign in
-
-
🔹 Day 52: Self Dividing Numbers (LeetCode #728) 📌 Problem Statement: A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is self-dividing because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Given two integers left and right, return a list of all self-dividing numbers in that range (inclusive). ✅ My Approach: I iterated through each number in the range [left, right] and checked if it was self-dividing using a helper function. For each number: Extract each digit using modulo and division. If any digit is zero or the number isn’t divisible by that digit, it’s not self-dividing. Otherwise, include it in the result list. 📊 Complexity: Time Complexity: O(n × d), where d is the number of digits. Space Complexity: O(1) (excluding the output list). ⚡ Submission Stats: Runtime: 2 ms (Beats 73.19%) Memory: 42.48 MB (Beats 10.09%) 💡 Reflection: This problem strengthened my skills in digit manipulation and modular arithmetic. It’s a great exercise for mastering number decomposition and iteration logic. ✨ #LeetCode #Java #Math #Loops #100DaysOfCode #Day52
To view or add a comment, sign in
-
-
🔍 Day 30 | Shift Happens (and That’s Beautiful) Today’s LeetCode challenge was #848 – Shifting Letters 🌀 At first glance, it looks like a simple “shift characters” task — but under the hood, it’s a neat example of prefix-sum logic meets modular arithmetic. 💡 The Problem: For each index i, shift the first i+1 letters by shifts[i] times — wrapping around from 'z' to 'a'. 🧠 The Trick: If we start from the end of the string and move backward, we can keep a cumulative shift sum that already accounts for all later shifts. This avoids repeatedly looping over the prefix and keeps our time complexity O(n) instead of O(n²). ⚙️ Approach: Traverse from right to left Keep adding each shift to a running total (totalShift) Apply totalShift % 26 to shift the current character efficiently Update the string using a StringBuilder 💨 Why It’s Optimal: ✅ Single pass — linear time ✅ Constant extra space ✅ Clean and scalable even for large inputs (up to 10⁵ length! Sometimes the cleanest solutions come from flipping your perspective — literally shifting your direction Shishir chaurasiya and PrepInsta #LeetCode #CodingChallenge #Java #Algorithms #ProblemSolving #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 87/100 of #100DaysOfCode 💡 Problem: 3321. Find X-Sum of All K-Long Subarrays II (Hard) 🔗 Platform: LeetCode Today’s challenge was all about optimizing sliding window logic with frequency-based ordering! The task — find the “x-sum” of every k-sized subarray, keeping only the top x most frequent elements (and if tied, prefer larger values). 🧠 Key Learnings: How to maintain frequency counts efficiently in a sliding window. Managing top-x elements dynamically using TreeSet and custom comparators. Overcoming TLE issues by switching from naive sorting (O(n*k)) to a balanced TreeSet approach (O(n log n)). ⚙️ Concepts Used: → Sliding Window → Frequency Map (HashMap) → Ordered Sets (TreeSet) → Custom Comparator Logic 🔥 This one really tested both logic & optimization — but once it clicked, it felt amazing! #LeetCode #100DaysOfCode #Java #CodingChallenge #ProblemSolving #DSA #SlidingWindow #Optimization
To view or add a comment, sign in
-
-
💻 Day 62 of #LeetCode100DaysChallenge Solved LeetCode 142: Linked List Cycle II — a problem that deepens understanding of linked list traversal and cycle detection using pointers. 🧩 Problem: Given the head of a linked list, return the node where the cycle begins. If there’s no cycle, return null. A cycle exists if a node can be revisited by continuously following the next pointer. The goal is to identify the exact node where the cycle starts — without modifying the list. 💡 Approach — Floyd’s Cycle Detection (Tortoise and Hare): 1️⃣ Use two pointers — slow and fast. 2️⃣ Move slow by 1 step and fast by 2 steps until they meet (if a cycle exists). 3️⃣ Once they meet, reset one pointer to the head. 4️⃣ Move both one step at a time; the node where they meet again is the start of the cycle. 5️⃣ If no meeting point (i.e., fast or fast.next becomes null), return null. ⚙️ Complexity: Time: O(N) — each pointer traverses the list at most twice. Space: O(1) — no extra memory used. ✨ Key Takeaways: ✅ Strengthened Floyd’s algorithm understanding for detecting and locating cycles. ✅ Learned how mathematical reasoning helps pinpoint the start node of a loop. ✅ Reinforced efficient use of pointer manipulation in linked list problems. #LeetCode #100DaysOfCode #Java #LinkedList #CycleDetection #FloydsAlgorithm #DSA #CodingJourney #WomenInTech #ProblemSolving
To view or add a comment, sign in
-
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