🚀 LeetCode #1281 | Simple Logic, Strong Foundation Sometimes the easiest problems build the strongest logic 💡 🔢 Problem: Given an integer "n", return the difference between the product of its digits and the sum of its digits. 👉 Example: Input: "n = 234" Product = 2 × 3 × 4 = 24 Sum = 2 + 3 + 4 = 9 Output = 24 - 9 = 15 --- 🧠 Approach (Step-by-Step): 1. Extract digits using "% 10" 2. Add digits → Sum 3. Multiply digits → Product 4. Return "product - sum" --- 💻 Java Code: class Solution { public int subtractProductAndSum(int n) { int sum = 0; int product = 1; while(n > 0){ int digit = n % 10; sum += digit; product *= digit; n /= 10; } return product - sum; } } --- 🎯 Key Learnings: ✔ Digit extraction using "%" and "/" ✔ Difference between accumulation (sum) & multiplication (product) ✔ Clean loop logic --- 💡 Real-Life Analogy: Think of digits as daily tasks: - Sum = total effort - Product = combined impact 👉 Result shows how much impact differs from effort! --- 🔥 Why this matters? Even simple problems sharpen your fundamentals — and strong basics = strong interviews 💪 --- #LeetCode #Java #Coding #DSA #ProblemSolving #Placements #SoftwareEngineer #LearningJourney
LeetCode 1281: Digit Product vs Sum in Java
More Relevant Posts
-
𝐃𝐚𝐲 𝟒𝟗 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on checking whether a string can be segmented into valid dictionary words. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Word Break 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐃𝐅𝐒 + 𝐌𝐞𝐦𝐨𝐢𝐳𝐚𝐭𝐢𝐨𝐧 • Converted the word list into a HashSet for fast lookup • Used recursion to try breaking the string into prefixes • If prefix exists in dictionary, recursively check the remaining string • Stored results in a memo map to avoid recomputation This avoids exponential re-checking of the same substrings. 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Memoization helps optimize recursive solutions • Breaking problems into smaller substrings is a common pattern • HashSet improves lookup efficiency • DP problems often start with recursion and get optimized 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n²) (with memoization) • Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When recursion feels slow, adding memoization can transform it into an efficient solution. 49 days consistent 🚀 On to Day 50. #DSA #Arrays #DynamicProgramming #Recursion #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Classical Backtracking Problem with a Classical Approach Solved Word Search (LeetCode 79) using a clean and intuitive DFS + Backtracking strategy Approach (Simple & Clear): •Start from every cell that matches the first character of the word. •Use DFS (Depth-First Search) to explore all 4 directions (up, down, left, right). •Mark the current cell as visited (by replacing it temporarily) to avoid revisiting. •If the full word is matched → return true immediately. •Backtrack by restoring the cell when the path doesn’t work. Key Insight: We explore all possible paths, but prune early when characters don’t match — this keeps the solution efficient. ⏱️ Time Complexity: 👉 O(m × n × 4^L) •m × n → starting points •4^L → exploring 4 directions for each character of length L 📌 Space Complexity: 👉 O(L) (recursion stack) 🔥 Clean recursion + smart backtracking = problem cracked! #DSA #Backtracking #LeetCode #CodingInterview #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 17/30– DSA Challenge 📌 LeetCode Problem – Plus One 📝 Problem Statement You are given a large integer represented as an array of digits. Increment the integer by one and return the resulting array. 📌 Example Input: digits = [1,2,3] Output: [1,2,4] 📌 Edge Case Input: [9,9,9] Output: [1,0,0,0] 💡 Key Insight Addition starts from the last digit. 👉 If digit < 9 → just add 1 and return 👉 If digit == 9 → it becomes 0 and carry moves left If all digits are 9 → create a new array. 🚀 Algorithm 1️⃣ Traverse from right → left 2️⃣ If digit < 9: Increment it Return array 3️⃣ Else: Set digit = 0 Continue 4️⃣ If loop ends → all were 9 Create new array of size n+1 Set first element = 1 ✅ Java Code (Optimal O(n)) class Solution { public int[] plusOne(int[] digits) { for (int i = digits.length - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } // All digits were 9 int[] result = new int[digits.length + 1]; result[0] = 1; return result; } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) (except edge case) 📚 Key Learnings – Day 17 ✔ Handle carry carefully ✔ Think from right to left ✔ Edge cases matter more than logic here ✔ Small problems test attention to detail Simple idea. Tricky edge case. Clean implementation. Day 17 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode
To view or add a comment, sign in
-
-
🚀 DAY 94/150 — CONNECTING TREE LEVELS! 🌳🔗 Day 94 of my 150 Days DSA Challenge in Java and today I solved a very interesting problem that focuses on level connections in Binary Trees 💻🧠 📌 Problem Solved: Populating Next Right Pointers in Each Node 📌 LeetCode: #116 📌 Difficulty: Medium 🔹 Problem Insight The task is to connect each node’s next pointer to its right node on the same level. If there is no right node → set next = null. 👉 This problem is based on a perfect binary tree, which allows some optimizations. 🔹 Approaches Used ✅ Approach 1: BFS (Level Order Traversal) • Use a queue to traverse level by level • Connect nodes within the same level using a prev pointer ✔️ Easy to understand ❌ Uses extra space (queue) ✅ Approach 2: Optimized (Constant Space) • Use already established next pointers • Connect: left → right right → next.left ✔️ No extra space (O(1)) ✔️ More optimized and elegant ⏱ Complexity Time Complexity: O(n) Space Complexity: • BFS → O(n) • Optimized → O(1) 🧠 What I Learned • Same problem can have multiple approaches (basic → optimized) • Perfect binary tree structure helps reduce complexity • Using existing pointers smartly can eliminate extra space 💡 Key Takeaway This problem taught me: How to connect nodes level-wise Difference between BFS vs pointer-based optimization Writing space-efficient solutions 🌱 Learning Insight Now I’m focusing more on: 👉 Moving from brute-force → optimized solutions 🚀 ✅ Day 94 completed 🚀 56 days to go 🔗 Java Solution on GitHub: 👉 https://lnkd.in/gDWj7K5Q 💡 Optimization is about using what you already have. #DSAChallenge #Java #LeetCode #BinaryTree #BFS #DFS #Pointers #150DaysOfCode #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
-
🔥 Day 59/100 – LeetCode Challenge 📌 Problem Solved: Remove Duplicates from Sorted Array II (Medium) Today’s problem was a great exercise in in-place array manipulation and two-pointer technique. 💡 Key Idea: Since the array is already sorted, duplicates are adjacent. Instead of removing all duplicates, we allow each element to appear at most twice. 👉 The trick is to compare the current element with the element at index k-2. If they are the same → skip ❌ If different → keep it ✅ ⚙️ Approach: Initialize pointer k = 2 Traverse from index 2 Copy valid elements forward Maintain order without extra space 🧠 What I learned: How to efficiently handle constraints like “at most twice” Importance of thinking in terms of index relationships (k-2) Writing optimal O(n) solutions with O(1) space 📊 Performance: ⚡ Runtime: 0 ms (100%) 💾 Memory: 48.46 MB 💻 Tech Used: Java Consistency is key 🔑 — 59 days done, 41 more to go! #100DaysOfCode #LeetCode #Java #DataStructures #CodingChallenge #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
Most people try to solve 3Sum using 3 nested loops. That solution works... but it's O(n³) and too slow. Today I learned how to reduce it to O(n²). 🚀 Day 81/365 — DSA Challenge Solved: 3Sum 🧠 The Idea Steps: 1. Sort the array 2. Fix one number 3. Use two pointers to find the other two numbers 4. Skip duplicates to avoid repeating triplets ⏱ Complexity Approach & Time 3 loops -> O(n³) Sort + Two pointers -> O(n²) Big improvement. 💡 What I learned today Whenever you see: • Sorted array • Pair sum • Triplet sum • Target sum Think: Sort + Two Pointers Day 81/365 complete. Still learning. Still coding. Code: https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #100DaysOfCode #365Days365DSAProblems
To view or add a comment, sign in
-
📘 DSA Journey — Day 29 Today’s focus: Binary Search on answer space. Problem solved: • Find Peak Element (LeetCode 162) Concepts used: • Binary Search • Observing slope / trend • Search space reduction Key takeaway: The goal is to find a peak element (an element greater than its neighbors). Instead of checking all elements, we use binary search by observing the slope: • If nums[mid] < nums[mid + 1] → we are on an increasing slope, so a peak must exist on the right side • Else → we are on a decreasing slope, so a peak lies on the left side (including mid) By following this logic, we eliminate half of the search space each time and find a peak in O(log n) time. The key insight is: A peak is guaranteed to exist, and the direction of slope helps guide the search. Continuing to strengthen binary search intuition and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
. 🚀 Day 27/30 – DSA Challenge 📌 LeetCode Problem – Middle of the Linked List 📝 Problem Statement Given the head of a singly linked list, return the middle node of the linked list. 👉 If there are two middle nodes, return the second middle node. 📌 Example Input: 1 → 2 → 3 → 4 → 5 Output: 3 📌 Even Case Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 4 💡 My Approach (Counting Method) Instead of using two pointers, I used a two-step approach: 👉 First count total nodes 👉 Then move to the middle 🚀 Algorithm 1️⃣ Traverse the list and count nodes 2️⃣ Calculate middle index: mid = count / 2 3️⃣ Traverse again till mid position 4️⃣ Return that node ✅ Java Code class Solution { public ListNode middleNode(ListNode head) { int count = 0; ListNode temp = head; // Step 1: Count nodes while (temp != null) { count++; temp = temp.next; } // Step 2: Find middle index int mid = count / 2; // Step 3: Traverse to middle temp = head; for (int i = 0; i < mid; i++) { temp = temp.next; } return temp; } } ⏱ Complexity Time Complexity: O(n) (two traversals) Space Complexity: O(1) 📚 Key Learnings – Day 27 ✔ Problems can have multiple valid approaches ✔ Counting method is simple and intuitive ✔ Always think about optimizing further ✔ Same problem can be solved in one pass using fast & slow pointers Simple idea. Clear logic. Solid understanding. Day 27 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 72 – DSA Journey | Reversing a Sublist in Linked List Continuing my daily DSA practice, today I worked on a classic linked list problem that tested my understanding of pointer manipulation and in-place reversal. 📌 Problem Practiced: Reverse Linked List II (LeetCode 92) 🔍 Problem Idea: Reverse a portion of a linked list between given positions left and right, without affecting the rest of the list. 💡 Key Insight: Instead of reversing the entire list, the trick is to re-link nodes within the given range by carefully adjusting pointers. 📌 Approach Used: • Use a dummy node to handle edge cases • Traverse to the node just before left • Iteratively move nodes to the front of the sublist • Maintain connections with the remaining list 📌 Concepts Strengthened: • Linked list traversal • Pointer manipulation • In-place reversal • Handling edge cases ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) 🔥 Today’s takeaway: Small pointer changes can drastically transform a data structure — understanding them deeply is key. On to Day 73! 🚀 #Day72 #DSAJourney #LeetCode #LinkedList #Java #ProblemSolving #Coding #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
🚀 Day 67 – DSA Journey | Converting Binary Linked List to Integer Continuing my daily DSA practice, today I solved another linked list problem on LeetCode focusing on number conversion and traversal. 📌 Problem Practiced: Convert Binary Number in a Linked List to Integer (LeetCode 1290) 🔍 Problem Idea: Given a linked list where each node contains 0 or 1, convert the binary number into its decimal equivalent. 💡 Key Insight: Instead of storing the binary number, we can directly compute the decimal value while traversing the list using the formula: result = result * 2 + current value. 📌 Approach Used: • Initialize result as 0 • Traverse the linked list • At each node → multiply result by 2 and add current value • Return final result 📌 Concepts Strengthened: • Linked list traversal • Binary to decimal conversion • Iterative computation • Space optimization ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) 🔥 Today’s takeaway: You don’t always need extra storage—sometimes you can compute results on the go efficiently. On to Day 68! 🚀 #Day67 #DSAJourney #LeetCode #LinkedList #Java #ProblemSolving #Coding #LearningInPublic #Consistency
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