Day 4 of #100DaysOfCode Solved: Rotate Function (LeetCode 396) Approach 1: Brute Force Rotate array each time → O(n) Recalculate F(k) → O(n) Total: O(n²) (Too slow) Approach 2: Optimized (Using Relation) Instead of recomputing, reuse the previous value: Each rotation shifts elements by +1 index Last element moves to index 0 Use relation to compute next value in O(1) Total: O(n) Key Intuition: When array rotates: Every element’s contribution increases by its value But we subtract n × last element to adjust Takeaway: Whenever a problem involves repeated recomputation after shifts/rotations look for a mathematical relation #LeetCode #DSA #CodingInterview #ProblemSolving #100DaysOfCode
Rotate Function Optimized with Relation
More Relevant Posts
-
-- Solved LeetCode 100: Same Tree -- Today I worked on the classic binary tree problem “Same Tree”, and it turned out to be a great exercise in strengthening recursion fundamentals -- Problem Summary: -- Given two binary trees, determine whether they are identical in both structure and node values. -- Approach (Recursive DFS): At each node, I focused on 3 key checks: • If both nodes are NULL → trees match at this point • If one is NULL → structure mismatch • If values differ → not the same If all checks pass, recursively compare left and right subtrees. -- Complexity: Time: O(n) – visiting every node once Space: O(h) – recursion stack (depends on tree height) Consistency > Complexity. #LeetCode #DSA #Recursion #BinaryTree #CodingJourney #SoftwareEngineering #algorithm
To view or add a comment, sign in
-
-
LeetCode Daily | Day 72 🔥 LeetCode POTD – 3653. XOR After Range Multiplication Queries I (Medium) ✨ 📌 Problem Insight Given an array and queries: ✔ Each query updates indices in a range [l, r] ✔ Jump pattern using step k (i.e., l, l+k, l+2k...) ✔ Multiply elements by v under modulo ✔ Finally compute XOR of entire array 🔍 Initial Thinking – Direct Simulation ✅ 💡 Idea: ✔ For each query, iterate from l → r with step k ✔ Apply multiplication ✔ After all queries, compute XOR ⏱ Works because: ✔ Constraints are small (n, q ≤ 1000) ✔ Even worst case passes comfortably ⚠️ Common Pitfall ❌ 💡 Mistake: ✔ Misreading query format [l, r, k, v] ✔ Using wrong index for v 💡 Important Fix: ✔ Always use v = query[3] ✔ Use 1LL * a * b to avoid overflow 💡 Key Observation 🔥 ✔ This looks complex due to jumps (k) ✔ But no overlapping pattern optimization needed ✔ Pure simulation + careful coding is enough ⏱ Complexity: ✔ Time: O(q * n) ✔ Space: O(1) 🧠 Key Learning ✔ Not every problem needs optimization ✔ Read queries carefully (indexing matters!) ✔ Handle overflow using long long ✔ Simulation problems test implementation skills 🚀 Takeaway A clean simulation problem where correctness > complexity — perfect for building attention to detail ⚡ #LeetCode #DSA #Algorithms #CPlusPlus #ProblemSolving #CodingJourney #DataStructures
To view or add a comment, sign in
-
-
Day 46 Today I solved: Binary Search (LeetCode 704) 💡 Problem: Given a sorted array, find the index of a target element. If it doesn’t exist, return -1. 💡 My Approach: I used the classic Binary Search technique: 1️⃣ Initialize two pointers: start and end 2️⃣ Find middle index mid 3️⃣ Compare nums[mid] with target 👉 If equal → return mid 👉 If target is greater → search right half 👉 If target is smaller → search left half 4️⃣ Repeat until found or search space is exhausted 💡 Key Insight: Instead of checking every element ❌ Divide the search space in half each time ✅ ⚡ Complexity: Time: O(log n) Space: O(1) #LeetCode #DSA #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
🚀 Day 8 of #LeetCodeDailyChallenge Some problems are not about logic alone… but handling messy real-world input 😵💫 📌 Today’s problem: String to Integer (atoi) 📍 Topic: Strings / Parsing ⚡ Difficulty: Medium What I learned today: 🔹 Ignoring leading whitespaces correctly 🔹 Handling signs (+ / -) carefully 🔹 Converting characters to digits step-by-step 🔹 Stopping at invalid characters (important edge case!) 🔹 Handling overflow within 32-bit integer range At first, it felt like simple conversion… But managing all edge cases together made it challenging 🤯 This problem reminded me: 👉 Real-world data is messy — code should handle it 👉 Edge cases + conditions = actual problem-solving Slowly improving not just coding… but handling complexity 🔥 #DSA #LeetCode #Strings #Parsing #ProblemSolving #LearningInPublic #Consistency #KeepGoing
To view or add a comment, sign in
-
Day 85 / 100 – 100 Days of LeetCode Challenge 🚀 Problem: Alternating Digit Sum (LeetCode #2544) Today I solved the Alternating Digit Sum problem. The task is to calculate the alternating sum of the digits of a number, where digits in odd positions are added and digits in even positions are subtracted. Approach I extracted each digit of the number from left to right and alternated between addition and subtraction using a sign variable. This allowed me to compute the result efficiently without storing extra data structures. Steps followed: • Convert the number into digits • Initialize a sign variable starting with positive • Add or subtract digits based on the current sign • Flip the sign after processing each digit • Return the final alternating sum This approach keeps the logic simple and efficient using basic arithmetic operations. Complexity Time Complexity: O(d) (where d is the number of digits) Space Complexity: O(1) Result ✔ Accepted ⚡ Efficient runtime 🧠 Simple arithmetic logic A good problem to strengthen understanding of number manipulation and digit processing techniques. #100DaysOfCode #100DaysLeetCodeChallenge #LeetCode #DSA #CPlusPlus #ProblemSolving #Math #Numbers
To view or add a comment, sign in
-
-
LeetCode Daily | Day 78 🔥 LeetCode POTD – 3488. Closest Equal Element Queries (Medium) ✨ 📌 Problem Insight Given a circular array: ✔ For each query index, find nearest same value ✔ Distance is circular ✔ Return minimum distance ✔ If no same value exists → return -1 🔍 Initial Thinking – Brute Force ⚙️ 💡 Idea: ✔ For each query, scan entire array ✔ Check all indices with same value ⚠️ Problem: ✔ O(n) per query → too slow ✔ Total becomes O(n²) in worst case 💡 Key Observation 🔥 ✔ Same values repeat → group their indices ✔ Nearest answer lies among adjacent indices in that group ✔ Circular distance: → min(|i - j|, n - |i - j|) 🚀 Optimized Approach ✔ Store indices for each value (hash map) ✔ For each query: → Use binary search to find position → Check nearest left & right indices ✔ Handle circular wrap using modulo 🔧 Core Idea ✔ Reduce search space using grouping ✔ Use binary search for nearest neighbors ✔ Apply circular distance formula ⏱ Complexity ✔ Time: O(n + q log n) ✔ Space: O(n) 🧠 Key Learning ✔ Nearest element problems → check neighbors, not all ✔ Preprocessing (grouping) can drastically optimize queries ✔ Circular arrays often need wrap-around handling 🚀 Takeaway A great mix of hashing + binary search + circular logic — classic interview pattern to reduce brute force into efficient queries ⚡ #LeetCode #DSA #Algorithms #CPlusPlus #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 46 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Geometric Sum using Recursion We were given an integer n. Task was to find the sum: 1 + 1/3 + 1/3² + ... + 1/3ⁿ Using recursion. 💻 Approach 🔹️Define a recursive function sum(n). 🔹️Base case: ▪️If n == 0 → return 1 🔹️Recursive case: ▪️Return sum(n-1) + 1/(3ⁿ) Each call adds one term. And moves toward smaller n. 📊 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) Due to recursion stack. 📚 What I learned today: ▫️Recursion can be used for summation of series. ▫️Each recursive call adds one term to the result. ▫️Understanding base case is important to stop recursion. ▫️Power calculations are common in series problems. Day 46 completed. Getting more comfortable with recursive formulas 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Day 67/150 🚀 LeetCode 912: Sort an Array 🧠 Problem Given an integer array nums, sort the array in ascending order without using built-in sorting functions. 📌 Example Input → nums = [5,2,3,1] Output → [1,2,3,5] 💡 Approach (Merge Sort) • Divide array into two halves • Recursively sort left half • Recursively sort right half • Merge sorted halves ⚡ Example Walkthrough [5,2,3,1] → Divide → [5,2] [3,1] → Sort → [2,5] [1,3] → Merge → [1,2,3,5] ⏱ Time Complexity O(n log n) 📦 Space Complexity O(n) ✅ Result: Accepted ⚡ Runtime: 70 ms (Beats 60.61%) Strengthening sorting fundamentals with Merge Sort 🔥 Consistency continues — Day 67 complete 🚀 #Day67 #LeetCode #DSA #MergeSort #Sorting #CodingJourney #ProblemSolving #SoftwareEngineering #TopInterview150
To view or add a comment, sign in
-
-
Day 88 / 100 – 100 Days of LeetCode Challenge 🚀 Problem: Strictly Palindromic Number (LeetCode #2396) Today I solved the Strictly Palindromic Number problem. The task is to determine whether a given integer n is strictly palindromic in all bases from 2 to n−2. Approach Instead of converting the number into every base and checking manually, I analyzed the mathematical property of the problem. It turns out that for any integer n ≥ 4, the number cannot be strictly palindromic in all required bases. Therefore, the result will always be false. Steps followed: • Understand the definition of strictly palindromic numbers • Analyze the mathematical behavior of numbers in different bases • Apply the observation that such numbers do not exist for n ≥ 4 • Directly return false This approach avoids unnecessary computation and relies on mathematical reasoning. Complexity Time Complexity: O(1) Space Complexity: O(1) Result ✔ Accepted ⚡ Constant time solution 🧠 Mathematical insight-based optimization A good problem to strengthen understanding of mathematical reasoning and problem analysis. #100DaysOfCode #100DaysLeetCodeChallenge #LeetCode #DSA #CPlusPlus #ProblemSolving #Math #Logic
To view or add a comment, sign in
-
-
Day 167/365 – DSA Challenge 🚀 Solved Construct Binary Tree from Preorder and Inorder Traversal on LeetCode today. 🔹 Problem: Given two arrays — preorder and inorder traversal of a binary tree — construct the original tree. 🔹 Approach Used: Recursion + HashMap Steps followed: 1️⃣ First element of preorder → root 2️⃣ Find root in inorder using a hashmap (for O(1) lookup) 3️⃣ Split inorder into: Left subtree Right subtree 4️⃣ Recursively build left and right subtrees 🔹 Key Idea: Preorder gives the root, inorder gives the structure 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(n) 💻 Language: C++ This is a classic problem that tests your understanding of tree reconstruction + recursion depth control. #Day167 #365DaysOfCode #DSA #LeetCode #BinaryTree #Recursion #HashMap #CodingChallenge #Cpp
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