#100DaysOfLeetcode journey 🚀 Day 47/100 — Mathematical Symmetry in Matrix Rotations! Today’s Problem: 48. Rotate Image 🔹 The Goal: Rotate an $n \times n$ 2D matrix (representing an image) 90 degrees clockwise. The catch? It must be done in-place, meaning we can't allocate a second matrix to simplify the move. 🔹 The Insight: At first glance, moving every element to its new $(x, y)$ coordinate feels like a complex mapping nightmare. However, there is a beautiful geometric shortcut. A 90-degree clockwise rotation is equivalent to two simple operations: Transpose: Flip the matrix over its main diagonal. Reverse: Flip each row horizontally. 🔹 The Logic: In-Place Transpose: By swapping matrix[i][j] with matrix[j][i], we turn rows into columns. Row Reversal: Once transposed, reversing the elements in each row completes the clockwise shift. Efficiency: This approach uses $O(1)$ auxiliary space and $O(n^2)$ time, touching each element only twice. ✨ Achievement: Day 47! Successfully replaced a complex coordinate-mapping problem with a clean, two-step symmetry transformation. It’s a perfect example of how breaking a large problem into two fundamental geometric steps makes the code much more readable and easier to debug. 🔍 Steps followed: ✔ Diagonal Swapping: Implemented the transpose logic using nested loops with a j = i starting constraint. ✔ Symmetric Row Reversal: Used the two-pointer approach to flip rows in-place. ✔ Zero-Memory Footprint: Verified that no extra arrays were used, maintaining strict space efficiency. 🔧 Complexity Analysis: Time Complexity: $O(n^2)$ Space Complexity: $O(1)$ 47 days in! Sometimes the shortest path to a solution isn't a straight line—it's a flip and a reverse. 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #MatrixAlgorithms #Geometry #Optimization #Day47
Rotating Matrix 90 Degrees Clockwise in Place
More Relevant Posts
-
#100DaysOfLeetcode journey 🚀 Day 64/100 — Linear Search & Absolute Minimization! Today’s Problem: 1848. Minimum Distance to the Target Element 🔹 The Goal: Given an array, a target value, and a starting index, find the index $i$ where $nums[i] == target$ such that the absolute distance $|i - start|$ is minimized. 🔹 The Insight: While many distance-based problems involve complex sorting or two-pointer strategies, this one is beautifully straightforward. Because we need to find the absolute minimum distance, a single linear scan is all it takes to evaluate every potential candidate and keep track of the closest one. 🔹 The Logic: Exhaustive Search: We iterate through the entire array to ensure we don't miss any occurrences of the target. Distance Tracking: For every match, we calculate the absolute difference between the current index and our start point. Running Minimum: We maintain a minDistance variable that gets updated whenever a "closer" target is discovered. ✨ Achievement: Day 64! Only 36 days remaining until the century mark. Today was a great reminder that not every "Hard" problem requires a complex data structure—sometimes, the most robust solution is a clean, well-implemented linear scan. 🔍 Steps followed: ✔ Single-Pass Scan: Maintained a strictly $O(N)$ runtime. ✔ Distance Logic: Used Math.abs to handle indices on both the left and right sides of the start point. ✔ Constant Space: Kept the memory footprint at $O(1)$. 🔧 Complexity Analysis: Time Complexity: $O(N)$ Space Complexity: $O(1)$ 97 days down! The finish line is officially in sight. Let's finish these final three days with the same consistency that got us here! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #LinearSearch #Optimization #Algorithms #Day64
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 55/100 — Reversing Diagonal Transpositions! Today’s Problem: 2075. Decode the Slanted Ciphertext 🔹 The Goal: Decipher a string that was written diagonally into a matrix but read out row-by-row. We need to extract the original message and handle any padding spaces correctly. 🔹 The Insight: This is a classic "Coordinate Mapping" problem. When data is transformed from one traversal order (diagonal) to another (row-major), the key is to find the mathematical relationship between the indices. If a character is at row $i$ and starts at diagonal $j$, its column index is always $i + j$. 🔹 The Logic: Grid Mapping: By calculating cols = length / rows, we can treat the flat string as a 2D matrix without actually allocating any extra 2D space. Diagonal Scanning: I used a nested loop where the outer loop selects the starting "offset" (top-row column) and the inner loop moves down the diagonal. Precision Trimming: Since the cipher pads the matrix with spaces, the final step requires a backward-pass to remove trailing blanks while preserving spaces that were part of the original message. ✨ Achievement: Day 55! Successfully implemented a linear-time $O(N)$ decoding algorithm. Moving from backtracking and combinatorial searches into geometric string manipulation is a great way to maintain a diverse problem-solving toolkit. 🔍 Steps followed: ✔ Dimension Derivation: Computed the matrix footprint based on the input constraints. ✔ Index Calculation: Leveraged i * cols + (j + i) to access characters directly from the 1D string. ✔ In-Place Cleanup: Managed result trimming to ensure accuracy against the problem's whitespace rules. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(n)$ 83 days in! Only 17 more to go. The finish line is closer than ever! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #StringAlgorithms #MatrixManipulation #Algorithms #Day55
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 67/100 — Optimizing Circular Proximity! Today’s Problem: Minimum Circular Distance to Matching Elements 🔹 The Goal: Given an array that "wraps around," find the shortest path from a specific index to any other occurrence of the same value. 🔹 The Insight: A naive search for every query would be $O(Q \times N)$, which is catastrophic for large datasets. The breakthrough here is Spatial Indexing. By pre-grouping the indices of every value and keeping them sorted, we transform a global search into a localized neighbor check. 🔹 The Logic: Value-to-Index Mapping: I used a HashMap to store sorted lists of indices for each unique number. Logarithmic Search: Using binarySearch, I instantly located the query index within its value-group. The "Circular Sandwich": Because the indices are sorted, the closest matching elements are always the immediate neighbors in the list. By checking the left, the right, and the wrap-around (first/last) elements, we guarantee the global minimum in $O(\log N)$ time. ✨ Achievement: Day 67! Successfully applied pre-computation and binary search to optimize a spatial query problem. Understanding that the "closest" element in a circular topology is always an adjacent neighbor in the sorted index space is a powerful shortcut for range-based problems. 🔍 Steps followed: ✔ Map Pre-processing: Clustered indices for constant-time value lookups. ✔ Binary Search Integration: Optimized neighbor identification to logarithmic time. ✔ Modular Distance Logic: Correctly handled the $N - \text{linearDist}$ calculation for circular boundaries. 🔧 Complexity Analysis: Time Complexity: $O(N + Q \log N)$ Space Complexity: $O(N)$ 67 days down! The logic is getting faster, and the problems are getting more interesting. Let's keep the streak alive! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #ArrayAlgorithms #BinarySearch #Optimization #Day67
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 🚀 Day 68/100 — Numerical Symmetry & Mirror Distances! Today’s Problem: Mirror Distance of an Integer 🔹 The Goal: Define the "Mirror Distance" of a number $n$ as the absolute difference between the number and its digit-reversal. For example, if $n = 123$, the mirror is $321$, and the distance is $|123 - 321| = 198$. 🔹 The Insight: This is a fundamental exercise in Digit Manipulation. Reversing a number isn't just a string operation; it’s an arithmetic process. By using the modulo operator (% 10) to extract the last digit and integer division (/ 10) to shift the decimal place, we can reconstruct the mirror image in a single pass. 🔹 The Logic: Arithmetic Reversal: I used a while-loop to peel off digits and build the reversed integer. This naturally handles the "omit leading zeros" rule (e.g., reversing $120$ results in $21$ because $0 \times 10 + 2 \times 1 + 1$ arithmetic logic). Absolute Variance: The final result is simply the absolute magnitude of the gap between the two values. Negative Handling: I ensured the logic remains robust for negative integers by reversing the absolute value and reapplying the sign. ✨ Achievement: Day 68! We are well into the second half of the challenge. Today’s solution highlights how core arithmetic can replace heavy string parsing for better performance and lower memory overhead. 🔍 Steps followed: ✔ Digit Extraction: Peeling digits using remainder operations. ✔ Numerical Reconstruction: Building the reversed value through decimal shifting. ✔ Error Guarding: Managed potential sign issues to ensure a valid absolute distance. 🔧 The Stats: Time Complexity: $O(\log_{10} n)$ Space Complexity: $O(1)$ 68 days down! The journey into algorithmic mastery continues. Let's keep the momentum! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #MathAlgorithms #Logic #Optimization #Day68
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 🚀 Day 73/100 — Budgeting Increments with Sliding Windows! Today’s Problem: 1838. Frequency of the Most Frequent Element 🔹 The Goal: Maximize the frequency of any element in an array by increasing other elements. You have a "budget" of $k$ total increments. 🔹 The Insight: This is a classic Sorting + Sliding Window challenge. By sorting the data, we ensure that elements that require the least work to become identical are grouped together. The problem then shifts from a search for "which value" to a search for "how wide a window" can we afford. 🔹 The Logic: The Cost Equation: For any window ending at right, the cost to make everything equal to nums[right] is simply $(Value \times Size) - \text{Total Sum}$. Greedy Expansion: We keep expanding the right pointer and adding to our window sum. Dynamic Contraction: The moment our "cost to equalize" exceeds our budget $k$, we shrink the window from the left until it’s affordable again. Efficiency: This allows us to find the global maximum frequency in a single linear sweep after sorting. ✨ Achievement: Day 73! We're deep into the final 30% of the challenge. Moving from prefix-sum coordinate math to these dynamic-cost sliding windows is refining my ability to handle optimization problems with multiple constraints. 🔍 Steps followed: ✔ Sort & Proximity: Grouped similar values to minimize increment costs. ✔ Long-Precision Math: Used long to prevent overflow when calculating window areas. ✔ Linear Synchronization: Implemented the two-pointer sweep for an efficient $O(N \log N)$ total runtime. 🔧 The Stats: Time Complexity: $O(n \log n)$ Space Complexity: $O(1)$ 73 days down! The logic is getting faster and the solutions are getting cleaner. Let’s keep going! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #SlidingWindow #Sorting #Optimization #Day73
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 🚀 Day 72/100 — Hamming Distance & Early-Exit Optimization! Today’s Problem: 2452. Words Within Two Edits of Dictionary 🔹 The Goal: Given a set of query words and a dictionary, identify which queries can be transformed into any dictionary word using a maximum of two character replacements. 🔹 The Insight: This is a classic "String Similarity" problem. Since all words are guaranteed to have the same length, the number of edits required is simply the Hamming Distance—the count of positions where characters differ. 🔹 The Logic: Exhaustive Comparison: For each query, we check it against the dictionary entries until we find a match within the 2-edit threshold. The Early Break (Pruning): This is the key optimization. While comparing two words character by character, if the difference count (diff) exceeds 2, we immediately stop and move to the next dictionary word. Short-Circuiting: Once a query word is validated against any dictionary word, we add it to our results and immediately move to the next query, avoiding unnecessary comparisons. ✨ Achievement: Day 72! Moving into the final 30 days of the challenge. Today’s solution highlights how simple logic—like breaking a loop early when a threshold is breached—can significantly improve the performance of $O(N \cdot M)$ algorithms without the complexity of more advanced data structures like Tries. 🔍 Steps followed: ✔ Hamming Distance Logic: Calculated positional differences for equal-length strings. ✔ Threshold Gating: Implemented a diff > 2 check to prune redundant character comparisons. ✔ Order Preservation: Ensured the results followed the original query sequence. 🔧 The Stats: Time Complexity: $O(Q \cdot D \cdot L)$ (where $Q$ is queries, $D$ is dictionary size, and $L$ is word length) Space Complexity: $O(1)$ auxiliary space. 72 days down! The logic is getting sharper, and the finish line is coming into focus. Let’s keep pushing! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #StringAlgorithms #Optimization #Algorithms #Day72
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 50/100 — The 50% Milestone & Parity Invariants! Today’s Problem: 2840. Check if Strings Can be Made Equal With Operations II 🔹 The Goal: I’ve officially reached the halfway point of the 100-day challenge! Today’s task was to determine if two strings of length $n$ can be made identical by swapping characters whose indices have the same parity (even with even, odd with odd). 🔹 The Insight: This is a classic "Track-Based" permutation problem. When you can only swap indices with an even difference ($j - i = 2, 4, \dots$), you aren't really dealing with one string—you're dealing with two independent character sets living in parallel. Characters at even positions can never migrate to odd positions, no matter how many swaps you perform. 🔹 The Logic: Decoupling: I split the character counts into two tracks: Even and Odd. Frequency Matching: Instead of simulating swaps (which would be $O(n^2)$), I used frequency arrays to verify if the "ingredients" for each track were identical between both strings. Efficiency: This reduction turns a permutation problem into a single-pass $O(n)$ validation with constant $O(1)$ auxiliary space. ✨ Achievement: Day 50! Crossing the halfway mark with a 100% efficient solution. It’s a powerful reminder that identifying what cannot change (invariants) is often the fastest way to solve what can change (permutations). 🔍 Steps followed: ✔ Parity Isolation: Used modulo logic to bin characters into even and odd frequency maps. ✔ Linear Synchronization: Processed both strings in a single loop to minimize cache misses. ✔ Array Comparison: Used Arrays.equals for a constant-time check against the 26-character alphabet. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ 50 days down, 50 to go. The momentum is undeniable. Let's finish the second half! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #StringAlgorithms #Parity #Optimization #Day50 #HalfwayMark
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 66/100 — Optimizing Circular Proximity! Today’s Problem: Minimum Circular Distance to Matching Elements 🔹 The Goal: Given an array that "wraps around," find the shortest path from a specific index to any other occurrence of the same value. 🔹 The Insight: A naive search for every query would be $O(Q \times N)$, which is catastrophic for large datasets. The breakthrough here is Spatial Indexing. By pre-grouping the indices of every value and keeping them sorted, we transform a global search into a localized neighbor check. 🔹 The Logic: Value-to-Index Mapping: I used a HashMap to store sorted lists of indices for each unique number. Logarithmic Search: Using binarySearch, I instantly located the query index within its value-group. The "Circular Sandwich": Because the indices are sorted, the closest matching elements are always the immediate neighbors in the list. By checking the left, the right, and the wrap-around (first/last) elements, we guarantee the global minimum in $O(\log N)$ time. ✨ Achievement: Day 66! Successfully applied pre-computation and binary search to optimize a spatial query problem. Understanding that the "closest" element in a circular topology is always an adjacent neighbor in the sorted index space is a powerful shortcut for range-based problems. 🔍 Steps followed: ✔ Map Pre-processing: Clustered indices for constant-time value lookups. ✔ Binary Search Integration: Optimized neighbor identification to logarithmic time. ✔ Modular Distance Logic: Correctly handled the $N - \text{linearDist}$ calculation for circular boundaries. 🔧 Complexity Analysis: Time Complexity: $O(N + Q \log N)$ Space Complexity: $O(N)$ 67 days down! The logic is getting faster, and the problems are getting more interesting. Let's keep the streak alive! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #ArrayAlgorithms #BinarySearch #Optimization #Day66
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 66/100 — Thinking in Circles! Today’s Problem: 2515. Shortest Distance to Target String in a Circular Array 🔹 The Goal: Find the shortest path between a starting index and a target string in an array that "wraps around" at the ends. You can move either clockwise or counter-clockwise. 🔹 The Insight: This is a beautiful exercise in Radial Geometry applied to a 1D structure. When you connect the ends of an array, the distance between any two points $i$ and $j$ isn't just $|i - j|$. There's a hidden path that goes through the "boundary" of the array. The shortest path is always the minimum of the direct linear distance and the "complement" distance ($N - \text{Linear Distance}$). 🔹 The Logic: Single Pass Scan: Instead of complex BFS, we just need to identify where the target lives. Dual-Distance Logic: For every match found, we evaluate the two possible routes: The "Standard" route (staying within the array bounds). The "Circular" route (jumping from index 0 to $N-1$ or vice versa). Constant Space: The entire check happens in $O(N)$ time with $O(1)$ memory. ✨ Achievement: Day 66! Moving from complex bitwise validation and string parsing into circular array logic. It’s a great reminder that understanding the topology of your data structure (whether it's a line, a circle, or a grid) is the first step toward optimization. 🔍 Steps followed: ✔ Linear Traversal: Evaluated every potential target location. ✔ Modular Arithmetic: Simplified circular transitions using absolute differences. ✔ Optimal Minimum: Tracked the global minimum across all valid occurrences. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ 66 days down! The finish line is coming into focus. Let’s keep the momentum! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #SoftwareEngineer #InternshipBound #Programming #ArrayAlgorithms #CircularArrays #Optimization #Day66
To view or add a comment, sign in
-
-
Day 71/120: Multi-Source Graph Traversal, Enterprise Execution, & Next-Gen R&D. The workload is scaling up. Balancing production tickets, academic evaluations, and algorithmic consistency requires strict pipeline management. -> Algorithmic Execution: Solved '01 Matrix'. Bypassed standard redundant traversal by engineering a Multi-Source Breadth-First Search (BFS) architecture. By initially queuing all zero-state nodes and expanding outward concurrently, I processed the shortest path for the entire matrix in a single O(N×M) pass, securing an 8ms runtime in the 90th percentile of C++ submissions. -> Enterprise Execution: Pushing through active sprint tasks at my Univ.live software engineering internship. Managing distributed state, resolving complex version control conflicts, and delivering code that directly impacts the production environment. -> Academics & Stealth R&D: Architected technical presentations for my upcoming university exams while laying down the initial system design specifications for a massive internal developer tool. Building the blueprint before I write the code. Optimize the graph. Manage the pipeline. Build the architecture. #120DaysOfCode #SoftwareEngineering #GraphAlgorithms #SystemDesign #DevOps #LeetCode #Cpp #BackendArchitecture
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