🔢 Today I worked on a classic matrix problem in Java — Diagonal Sum. The goal was simple: Calculate the sum of both the primary and secondary diagonals of a square matrix. Initially, I used a nested loop approach with O(n²) complexity. But then I optimized it to a clean O(n) solution by directly accessing diagonal indexes. While optimizing, I made an interesting mistake: ❌ I wrote if (i != matrix[i][matrix.length - 1 - i]) Here I accidentally compared an index with an element value. ✔ Correct approach: if (i != matrix.length - 1 - i) This ensures the center element in odd-sized matrices isn’t counted twice. 🧠 Key Learning: Indexes and values may look similar, but mixing them can break logic silently. Optimization is not just about speed — it’s about accuracy. #Java #leetcode #Coding #DSA #ProblemSolving #LearningInPublic #SoftwareEngineering
Optimized Java solution for Diagonal Sum problem in O(n) time
More Relevant Posts
-
Day 85 of #100DaysOfCode Solved Range Sum Query - Immutable (NumArray) in Java ➕ Approach Today's problem was a classic that demonstrates the power of pre-computation: finding the sum of a range in an array many times. The optimal solution is the Prefix Sum technique. Pre-computation: In the constructor, I built a prefixSum array where prefixSum[i] holds the sum of all elements from index 0 up to index $i-1$ in the original array. This takes $O(N)$ time. $O(1)$ Query: The magic happens in the sumRange(left, right) method. The sum of any range $[left, right]$ is found instantly by calculating prefixSum[right + 1] - prefixSum[left]. The cost of a single $O(N)$ setup is outweighed by the ability to perform every subsequent query in $O(1)$ time! #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #PrefixSum #Optimization #ProblemSolving
To view or add a comment, sign in
-
-
📌 Day 16/100 - Reverse String (LeetCode 344) 🔹 Problem: Reverse a given string in-place — meaning you must modify the original array of characters without using extra space. 🔹 Approach: Used the two-pointer technique — one starting at the beginning and one at the end of the array. Swap characters at both pointers, then move them closer until they meet. Efficient, clean, and runs in linear time without additional memory allocation. 🔹 Key Learnings: In-place algorithms optimize space complexity significantly. The two-pointer pattern is a versatile tool for many array and string problems. Understanding mutable vs immutable structures in Java is crucial for memory efficiency. Sometimes, the simplest logic beats the most complex one. 🧠 “True efficiency lies in simplicity, not complexity.” #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #TwoPointers
To view or add a comment, sign in
-
-
🧠 Daily LeetCode Grind — Java Edition Today’s challenge: ✅ Integer to Roman (#12 - Medium) 📌 Goal: Convert an integer to its equivalent Roman numeral representation using standard Roman numeral rules and subtractive notation. 📌 Approach: 🔹 Use two arrays — one for values and one for their corresponding Roman symbols. 🔹 Iterate from the largest value to the smallest, appending the corresponding Roman symbol while subtracting its value from the number. 🔹 Continue until the entire number is converted. 🔹 Handles subtractive cases like IV (4), IX (9), XL (40), XC (90), CD (400), and CM (900). 🧩 Test Case: Input: num = 3749 Output: "MMMDCCXLIX" 💡 Key Takeaways: 🔹 Strengthened understanding of greedy algorithms. 🔹 Learned efficient symbol mapping and iteration logic. 🔹 Improved clarity on how Roman numeral rules apply in algorithmic form. 💻 Language: Java 🧠 Complexity: O(1) — fixed number of Roman symbols and operations. #LeetCode #Java #CodingPractice #ProblemSolving #GreedyAlgorithm #DSA #DeveloperLife #CybernautEdTech #AcceptedSolution
To view or add a comment, sign in
-
-
📌 Day 12/100 - Concatenation of Array (LeetCode 1929) 🔹 Problem: Given an integer array nums, create a new array ans such that: ans[i] = nums[i] ans[i + n] = nums[i] where n is the length of nums. In short, we need to concatenate the array with itself to form a new array of size 2n. 🔹 Approach: First, determine the length n of the array. Create a new array newArray of size 2n. Loop through nums once: Assign each element twice — once at position i and once at position i + n. Finally, return the concatenated array. 🔹 Key Learning: Reinforced the concept of array indexing and iteration. Practiced efficient array manipulation in Java. Sometimes, the simplest logic is the cleanest — clarity beats complexity! 💡 Every solved problem adds a layer of confidence and consistency 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
To view or add a comment, sign in
-
-
Day 91 of #100DaysOfCode Solved Base 7 in Java 🔢 Approach The challenge was to convert a given integer (num) to its base 7 string representation. Conversion Method The core of the solution lies in the standard algorithm for base conversion: repeated division and remainder collection. Handle Zero and Negatives: If the input num is 0, the result is immediately "0". I determined if the number is negative and stored this in a boolean flag, then proceeded with the absolute value of the number (num = Math.abs(num)) for the conversion logic. Conversion Loop: I used a while loop that continues as long as num > 0. In each iteration: The remainder when num is divided by 7 (num % 7) gives the next digit in base 7. This digit is appended to a StringBuilder. num is then updated by integer division by 7 (num /= 7). Final Result: Since the remainders are collected in reverse order, I called sb.reverse(). If the original number was negative, I prepended a hyphen (-) to the reversed string. Finally, I returned the result as a string. This simple and efficient implementation had a very fast runtime, beating 77.39% of submissions. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #BaseConversion #ProblemSolving
To view or add a comment, sign in
-
-
Solved: LeetCode Problem 922 – Sort Array By Parity II 📌 Difficulty Level: Easy 💻 Language Used: Java 🧠 Topics: Arrays, Index Manipulation, Two-Pointer 🧩 Problem Overview: Rearrange the array so that elements at even indices are even numbers and elements at odd indices are odd numbers. 🎯 Key Learnings: ✅ Practiced separate pointer movement for even/odd indices ✅ Learned how to skip indices in steps of 2 for efficiency ✅ Strengthened control flow in condition-based pointer increment ✅ Designed an O(n) solution without extra space 🛠 Skills Practiced: Index Management Array Rearrangement Two-Pointer Optimization In-place Logic Building ⚡️ Problems like this sharpen thinking about index constraints and help in mastering array partitioning & arrangement patterns. #LeetCode #Java #RotateArray #ProblemSolving #Arrays #LogicBuilding #100DaysOfCode #CodeNewbie #TechCareers #WomenInTech #LearningInPublic #BuildInPublic #DeveloperJourney #CleanCode #DSA #AlgorithmPractice #CodingInterviewPrep #SoftwareDevelopment #AfrozCodes #DailyCoding #CrackTheCodingInterview #TechForAll
To view or add a comment, sign in
-
-
🧠 Today I revisited a classic problem — removing duplicates from a sorted array in Java. It’s simple at first glance, but understanding why it works step by step really clarifies how two-pointer logic shines in array problems. How it works: j scans the array k marks where the next unique value goes When nums[j] ≠ nums[j-1], copy and move k forward Example: Input → [1,1,2,2,3] Output → k = 3, unique elements = [1,2,3] ✅ Time: O(n) ✅ Space: O(1) #Java #ProblemSolving #Algorithms #Coding #LeetCode
To view or add a comment, sign in
-
-
Hii Connections 👋 Today I solved an interesting String problem in Java: Problem: Find the length of the longest substring without repeating characters. My Approach: I used the sliding window technique along with a Hashtable to track the last seen index of each character. Here’s the logic: Move a window through the string using two pointers (start and end). If a character repeats, move the start pointer just after the last occurrence of that character. Keep updating the maximum length (max) as the window expands. This approach efficiently solves the problem in O(n) time, avoiding unnecessary re-checks of characters. What I Learned: ✅ Sliding window works great for substring problems. ✅ Hashtable helps efficiently manage character indices. ✅ Optimization is often about tracking what you already know, not recalculating it. Another step forward in mastering DSA and pattern-based problem solving 💪 #Java #DSA #ProblemSolving #Coding #SlidingWindow #LeetCode #LearningEveryday
To view or add a comment, sign in
-
-
Day 39 — Ones and Zeroes (0–1 Knapsack Variation) Problem: 474. Ones and Zeroes Difficulty: Medium Language: Java Status: Solved Problem Summary: Given an array of binary strings strs and two integers m and n, find the maximum subset size such that the total number of '0's ≤ m and total '1's ≤ n. Key Concept: This is a 2D 0–1 Knapsack problem, where: Each string represents an item with two “weights”: count of '0's and '1's. We must maximize the number of strings (the “value”) within the constraints of available m and n. Algorithm Steps: Count zeros and ones for each string. Iterate backwards (to avoid overwriting previous states). Update dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1) for all valid i, j. Time Complexity: O(len(strs) * m * n) Space Complexity: O(m * n) Learning Takeaway: This problem strengthens understanding of multidimensional dynamic programming. The backward iteration pattern is crucial in 0–1 Knapsack-style DP to prevent reuse of the same item. #Day39 #100DaysOfCode #LeetCode #DynamicProgramming #Knapsack #DP #Java #Algorithms #CodingChallenge #ProblemSolving #DSA
To view or add a comment, sign in
-
-
#Day_28 Today’s problem was quite an interesting one — “Reach a Target Number” using minimal moves. 💡 Problem Summary: Starting from 0, on each move i, you can go either left or right by i steps. The goal is to find the minimum number of moves required to reach a given target. At first glance, it looked like a simple math problem, but the trick was to notice the parity condition — once the cumulative sum goes beyond the target, the difference (sum - target) must be even to allow flipping directions and still land exactly on target. Here’s the optimized logic I implemented in Java Key Takeaway: Sometimes, problems that look complex are just about observing patterns in numbers rather than brute force. A touch of math can simplify the entire logic! #100DaysOfCode #LeetCode #CodingChallenge #Java #ProblemSolving #DSA #LearnEveryday #CodingJourney
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