Day 105: Circular Arrays & Shortest Paths 🔄 Problem 2515: Shortest Distance to Target String in a Circular Array Today’s challenge involved finding the minimum steps to reach a target string in a circular array, allowing movement in both directions. The Strategy: • Bidirectional Search: Since the array is circular, the distance can be calculated in two ways: moving forward or moving backward. • Modular Arithmetic: I used (dist + n) % n to handle the wrap-around logic seamlessly, ensuring the index stays within bounds regardless of the direction. • Optimization: By iterating once through the array and comparing the distances for every occurrence of the target, I maintained an O(N) time complexity. Sometimes the most elegant way to handle a "circular" problem is simply embracing the symmetry of the path. 🚀 #LeetCode #Java #Algorithms #ProblemSolving #DailyCode
Circular Array Shortest Path in Java
More Relevant Posts
-
Day 12 of #100DaysOfCode — Sliding Window Today, I worked on the problem “Max Consecutive Ones III” LeetCode. Problem Summary Given a binary array, the goal is to find the maximum number of consecutive 1s if you can flip at most k zeros. Approach At first glance, this problem looks like a brute-force or restart-based problem, but the optimal solution lies in the Sliding Window technique. The key idea is to maintain a window [i, j] such that: The number of zeros in the window does not exceed k Expand the window by moving j Shrink the window by moving i whenever the constraint is violated Instead of restarting the window when the condition breaks, we dynamically adjust it. Key Logic Traverse the array using pointer j Count the number of zeros in the current window If zeros exceed k, move pointer i forward until the window becomes valid again At every step, update the maximum window size Why This Works This approach ensures: Each element is processed at most twice Time Complexity: O(n) Space Complexity: O(1) The most important learning here is understanding how to dynamically adjust the window instead of resetting it, which is a common mistake while applying sliding window techniques. In sliding window problems, always focus on expanding and shrinking the window efficiently rather than restarting the computation. #100DaysOfCode #DSA #SlidingWindow #LeetCode #Java #ProblemSolving #CodingJourney #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 566 of #750DaysOfCode 🚀 🔍 Problem Solved: Mirror Distance of an Integer Today’s problem was simple but a great reminder of how powerful basic number manipulation can be. 💡 Problem Insight: We define the mirror distance of a number as: 👉 abs(n - reverse(n)) So the task is: Reverse the digits of the number Compute the absolute difference 🧠 Approach: Extract digits using % 10 Build the reversed number Compute absolute difference 📊 Complexity: Time: O(d) → where d = number of digits Space: O(1) 🔥 Key Takeaway: Even the easiest problems reinforce fundamentals like digit extraction, reversal, and absolute difference — building blocks for more complex algorithms. #Day566 #750DaysOfCode #LeetCode #Java #CodingJourney #ProblemSolving #Algorithms #BeginnerFriendly
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved: Peak Index in a Mountain Array (#852) Today I solved the Peak Index in a Mountain Array problem using an optimized Binary Search approach. 💡 Approach: Instead of using a brute-force linear scan, I applied Binary Search to reduce the search space: Compare the middle element with its neighbors. If it's greater than both → it's the peak. If the sequence is increasing → move right. If decreasing → move left. ⚡ Time Complexity: O(log n) ⚡ Space Complexity: O(1) 📈 Performance: ✅ Runtime: 0 ms (Beats 100%) ✅ Efficient and scalable solution Consistency in problem-solving is the real game changer 💪 #LeetCode #DataStructures #Algorithms #BinarySearch #CodingJourney #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 86 – DSA Journey | Path Sum in Binary Tree Continuing my daily DSA practice, today I worked on a problem that strengthened my understanding of recursion and root-to-leaf traversal. 📌 Problem Practiced: Path Sum (LeetCode 112) 🔍 Problem Idea: Determine if there exists a root-to-leaf path in a binary tree such that the sum of node values equals a given target. 💡 Key Insight: Instead of tracking the full path, we can reduce the problem by subtracting the current node’s value from the target as we traverse down the tree. 📌 Approach Used: • If the node is null → return false • Check if it is a leaf node – If yes, compare node value with remaining target • Subtract current node value from target • Recursively check left and right subtrees • If any path matches → return true 📌 Concepts Strengthened: • Tree traversal • Recursion • Root-to-leaf path logic • Problem reduction technique ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(h) (recursion stack) 🔥 Today’s takeaway: Breaking down a problem step by step (reducing the target at each node) makes recursion much more intuitive. On to Day 87! 🚀 #Day86 #DSAJourney #LeetCode #BinaryTree #Recursion #Java #ProblemSolving #Coding #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
Day 16 of my #30DayCodeChallenge: Navigating the Twist! The Problem: Search in Rotated Sorted Array. The Logic: While a standard Binary Search assumes a fully linear sequence, a rotated array introduces a "break point." The key is realizing that at any given mid-point, at least one half of the array must be sorted. 1. Identify the Sorted Half: In every iteration, I compare nums [left] with nums [mid]. If nums [left] <= nums [mid], the left side is sorted. Otherwise, the right side is sorted. 2. Range Check: Instead of searching blindly, I check if the target actually lies within the bounds of that sorted half. 3. The Result: By consistently discarding half of the search space based on these sorted properties, we pinpoint the target index or return -1 if it doesn't exist. Cracking the code, one rotation at a time. Onward to Day 17! #Java #Algorithms #DataStructures #BinarySearch #ProblemSolving #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 45 of Daily DSA 🚀 Solved LeetCode 867: Transpose Matrix ✅ Problem: Given a 2D matrix, return its transpose (rows become columns and columns become rows). Approach: Created a new matrix and swapped indices while traversing. Steps: Get number of rows and columns Create a new matrix of size cols x rows Traverse original matrix Assign: trans[j][i] = matrix[i][j] Return the new matrix ⏱ Complexity: • Time: O(n × m) • Space: O(n × m) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.46 MB Simple transformations like transpose build strong fundamentals for matrix-based problems 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 55 of DSA – Median of Two Sorted Arrays Solved a hard binary search problem where we need to find the median of two sorted arrays in O(log(m+n)) time. 💡 Key Insight: Instead of merging both arrays, use binary search on partitions to directly find the correct median. ⚡ Approach: Find partition in the smaller array Adjust partition in the second array accordingly Check if left half and right half are valid Use boundary values to compute median ⏱️ Time Complexity: O(log(min(m, n))) 💾 Space Complexity: O(1) #DSA #LeetCode #Java #Algorithms #BinarySearch #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 56/100 | #100DaysOfDSA 🧠⚡ Today’s problem: String Compression A clean in-place array manipulation problem. Core idea: Compress consecutive repeating characters and store the result in the same array. Approach: • Traverse the array using a pointer • Count consecutive occurrences of each character • Write the character to the array • If count > 1 → write its digits one by one • Move forward and repeat Key insight: We don’t need extra space — just carefully manage read & write pointers. Time Complexity: O(n) Space Complexity: O(1) Big takeaway: In-place algorithms require precise pointer control but give optimal space efficiency. Mastering these improves real-world memory optimization skills. 🔥 Day 56 done. #100DaysOfCode #LeetCode #DSA #Algorithms #Strings #TwoPointers #InPlace #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
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