🚀 Day 56 of my #100DaysOfCode Journey Today, I solved LeetCode problem Reshape the Matrix Problem Insight: We are given a 2D matrix and two integers r and c. The task is to reshape the matrix into dimensions r × c while keeping the same elements in row-major order. If reshape is not possible, return the original matrix. Approach: • First, check if reshape is possible using condition → total elements must match (m × n == r × c) • Traverse the matrix using a single loop (treating it as a linear array) • Map old indices to new indices using division and modulo • Fill the new matrix in row-wise order Code Idea Used: Index mapping technique (1D simulation of 2D matrix) Time Complexity: O(m × n) | Space Complexity: O(1) (excluding output matrix) Key Takeaway: Understanding how to convert between 1D and 2D indexing (i/m, i%m) is very powerful for matrix transformation problems. #LeetCode #DSA #ProblemSolving #Java #CodingJourney #100DaysOfCode #Arrays #MatrixProblems
Reshaping a Matrix with LeetCode
More Relevant Posts
-
🚀 Day 37 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Transpose Matrix Problem Insight: Given a matrix, the task is to convert its rows into columns. If no transformation is possible in-place (for non-square matrices), we create a new matrix. Approach: • Identify number of rows and columns • Create a new matrix with reversed dimensions (col × row) • Traverse each element of the original matrix • Place elements by swapping indices → (i, j) becomes (j, i) Time Complexity: • O(m × n) — visiting each element once Space Complexity: • O(m × n) — due to new matrix creation Key Learnings: • Transpose = swapping row and column indices • Dimension handling is crucial to avoid errors • In-place transpose is only possible for square matrices Takeaway: A small change in indexing can completely transform how we view and solve a problem. #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving #Matrix
To view or add a comment, sign in
-
-
Day 100: Consistency, Growth, and a Milestone 💯 Problem 3740: Minimum Distance Between Three Equal Elements I Today marks 100 days of continuous problem-solving. While the number is just a marker, the real value has been the daily discipline of opening the IDE and tackling whatever challenge LeetCode throws my way. The Strategy: • Frequency Grouping: I used a HashMap to store a list of indices for every unique number in the array. This allowed me to isolate potential triplets instantly. • Sliding Window Logic: For any number appearing three or more times, I looked at a sliding window of three consecutive indices (i,i+1,i+2). • The Formula: Through testing, I identified that the minimum distance between three equal elements can be derived from the span between the first and third occurrence: (index of 3rd - index of 1st) * 2. • Optimization: By iterating through the pre-grouped index lists, I kept the solution efficient and clean. Reflecting on these 100 days, I’ve moved from basic simulations to complex optimizations like Square Root Decomposition and 3D DP. The goal isn't to stop here—it's to keep building, keep optimizing, and keep growing. 🚀 #LeetCode #Java #Algorithms #DataStructures #100DaysOfCode #Consistency #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
**Day 114 of #365DaysOfLeetCode Challenge** Today’s problem: **Keyboard Row (LeetCode 500)** A fun and simple problem focused on **strings + simulation + clean logic**. We need to return words that can be typed using letters from **only one row** of the American keyboard. Rows: * Row 1 → `qwertyuiop` * Row 2 → `asdfghjkl` * Row 3 → `zxcvbnm` 💡 **Core Idea:** For each word: 1️⃣ Convert to lowercase 2️⃣ Identify keyboard row of first character 3️⃣ Check whether every remaining character belongs to same row 📌 **Approach:** * Use strings to represent rows * Use `indexOf()` for membership check * Preserve original word in output ⚡ **Time Complexity:** O(total characters in all words) ⚡ **Space Complexity:** O(result list) **What I learned today:** Even easy problems teach valuable habits: 👉 Clean iteration 👉 Case handling 👉 Efficient validation logic 💭 **Key Takeaway:** Not every challenge needs advanced algorithms. Sometimes simplicity + clean implementation = best solution. #LeetCode #DSA #Strings #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
🔄 Solved “Spiral Matrix”, a classic matrix traversal problem using boundary-based approach. ✦ What This Problem Taught Me: • How to traverse a 2D matrix layer by layer using boundaries • Effective use of four pointers (top, bottom, left, right) • Managing direction-based traversal (→ ↓ ← ↑) • Importance of shrinking boundaries after each iteration • Avoiding duplicate traversals using proper conditions • Strengthened understanding of 2D arrays and indexing 🚀 Problems like this show how controlling boundaries and direction can simplify complex matrix traversals into a clean O(m × n) solution. On to solving more matrix and pattern-based problems 💪🔥 #LeetCode #DSA #Matrix #TwoPointers #CodingJourney #ProblemSolving #Java #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 LeetCode — Problem 8 | Day 13 💡 Problem: String to Integer (atoi) --- 🧠 Problem: Convert a string into a 32-bit signed integer (like C/C++ atoi). --- 🧠 Approach: - Skip leading whitespaces - Check sign (+ / -) - Convert digits one by one - Stop at first non-digit character - Handle overflow before it happens --- ⚙️ Core Logic: - Build number step-by-step: result = result * 10 + digit - Before adding digit, check: • If result > Integer.MAX_VALUE / 10 • Or result == MAX/10 and digit > 7 👉 Return: - Integer.MAX_VALUE (overflow) - Integer.MIN_VALUE (underflow) --- ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) --- ⚠️ Edge Cases: - " 42" → leading spaces - "-42" → negative number - "42abc" → stop at non-digit - "abc" → no digits → return 0 - Large values → handled overflow --- 🔍 Insight: Careful parsing is more important than complex logic --- 🔑 Key Learning: - Step-by-step string parsing - Handling edge cases cleanly - Preventing overflow before it occurs - Real-world input validation logic --- #LeetCode #DSA #Java #CodingJourney
To view or add a comment, sign in
-
-
Day 68/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Add Two Numbers A fundamental linked list problem that mimics real-life addition. Problem idea: Add two numbers represented by linked lists (digits stored in reverse order). Key idea: Linked list traversal + carry handling. Why? • We process digits one by one (like manual addition) • Need to handle carry at each step • Lists can have different lengths How it works: • Use a dummy node to build the result • Traverse both lists simultaneously • Add values + carry • Create new node with (sum % 10) • Update carry = sum / 10 • Move pointers forward • Continue until both lists and carry are done Time Complexity: O(max(m, n)) Space Complexity: O(max(m, n)) Big takeaway: Using a dummy node simplifies linked list construction and avoids edge cases. This pattern is very common in linked list problems. 🔥 Day 68 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #LinkedList #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 8/100 — #100DaysOfLeetCode Another day, another concept unlocked 💻🔥 ✅ Problem Solved: 🔹 LeetCode 73 — Set Matrix Zeroes 💡 Problem Idea: If any element in a matrix is 0, its entire row and column must be converted to 0 — and the challenge is to do this in-place without using extra space. 🧠 Algorithm & Tricks Learned: Instead of using extra arrays, we can use the first row and first column as markers. First pass → mark rows and columns that should become zero. Second pass → update the matrix based on those markers. Carefully handle the first row and first column separately to avoid losing information. ⚡ Key Insight: The matrix itself can act as storage, reducing extra memory usage. 📊 Complexity Analysis: Time Complexity: O(m × n) → traverse matrix twice Space Complexity: O(1) → solved in-place without extra data structures This problem taught me how small optimizations can significantly improve space efficiency. Learning to think beyond brute force every day 🚀 #100DaysOfLeetCode #LeetCode #DSA #MatrixProblems #Algorithms #Java #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 563 of #750DaysOfCode 🚀 📌 Problem Solved: Shortest Distance to Target String in a Circular Array Today I explored a clean and optimized approach to solving a circular array problem 🔄 💡 Key Insight: Instead of checking all indices, we can expand from the start index in both directions simultaneously 👉 At each step i, we check: Forward → (start + i) % n Backward → (start - i + n) % n ⏱️ The moment we find the target, we return i → which is guaranteed to be the minimum distance 🧠 Why this works: We are exploring layer by layer (like BFS on array) First match = shortest path ✅ No need to scan entire array unnecessarily 🔥 What I Learned: Circular problems can often be solved using modulo arithmetic Expanding outward is more efficient than brute force Think in terms of minimum steps, not positions Consistency is the real game changer 💯 On to Day 564 🚀 #LeetCode #Java #Algorithms #DataStructures #CodingJourney #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
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 27 of my #30DayCodeChallenge: The Efficiency of Binary Exponentiation! The Problem: Pow(x, n). Implementing the power function to calculate x". While it sounds simple, the challenge lies in handling large exponents (up to 231 - 1) and negative powers without hitting time limits or overflow. The Logic: This problem is a classic example of Divide and Conquer optimized through Binary Exponentiation (also known as Exponentiation by Squaring): 1. Bitwise Breakdown: Instead of multiplying x by itself n times (O(n)), we decompose n into powers of 2. For example, x13 is x8. x4. x¹. This brings our complexity down to O(log n). 2. The Iterative Jump: In every iteration of the loop, we square the current base (x = x x). If the current bit of n is 1 (checked via n & 1), we multiply our result by the current base. 3. Handling the Edge Cases: * Negative Exponents: If n is negative, we calculate xI" and then take the reciprocal (1/result). Overflow: We use a long for n during calculation to avoid overflow when converting -2, 147, 483, 648 to a positive value. The Calculation: By halving the power at each step, we transform a task that could take 2 billion operations into one that takes just 31. One step closer to mastery. Onward to Day 28! #Java #Algorithms #DataStructures #BinaryExponentiation #ProblemSolving #150DaysOfCode #SoftwareEngineer
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