🚀 Day 398 of #500DaysOfCode 🔹 Problem: 914. X of a Kind in a Deck of Cards 🔹 Difficulty: Easy 🔹 Language Used: Java ☕ 🧩 Problem Summary: Given a deck of cards where each card has an integer, the goal is to check if we can divide the deck into groups such that: Each group has exactly X cards, where X > 1, and All cards in a group have the same integer. If such a partition is possible, return true — otherwise, return false. 💡 Key Idea: The solution relies on finding the greatest common divisor (GCD) of all card frequencies. If the GCD of all counts is greater than 1, we can form valid groups; otherwise, we can’t. ⚙️ Approach: 1️⃣ Count the frequency of each card using a HashMap. 2️⃣ Compute the GCD of all frequency values. 3️⃣ If GCD > 1, return true; else, false. 🧠 Concepts Used: HashMap GCD (Euclidean Algorithm) Frequency Counting ✅ Example: Input: [1,2,3,4,4,3,2,1] → Output: true Input: [1,1,1,2,2,2,3,3] → Output: false 📘 Lesson Learned: Even simple-looking problems can hide elegant mathematical patterns. Understanding GCD turned out to be the key! 💪 #Day398 #Java #LeetCode #ProblemSolving #CodingChallenge #LearnEveryday #Programming #Developer #100DaysOfCode #500DaysOfCode
Solved LeetCode problem 914 with Java: X of a Kind in a Deck of Cards
More Relevant Posts
-
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 20 | LeetCode Challenge – Decode Ways (Problem #91) Today’s challenge involved decoding an encoded numeric string where each number represents a letter (A–Z). The task was to determine how many possible ways the message can be decoded. 💡 Core Concept: Each number from 1–26 maps to letters A–Z, and the challenge lies in handling overlapping combinations and invalid encodings (like “06”). 📘 Approach: Implemented a Dynamic Programming (DP) solution in Java. Used an integer array dp[] to store the number of decoding ways up to each position. Considered both single-digit and two-digit decodings: Single-digit → valid if between 1 and 9. Two-digit → valid if between 10 and 26. The result was stored in dp[n], representing all valid decoding combinations. ⚙️ Algorithm Used: Dynamic Programming 🧾 Language: Java ⚡ Runtime: 1 ms (Beats 83.21%) 💾 Memory: 43.33 MB 🧠 Insight: Breaking the decoding process into smaller subproblems allowed efficient computation of possible message interpretations. This problem elegantly demonstrates how DP handles overlapping substructures in combinatorial challenges. #Day20 #LeetCode #DecodeWays #DynamicProgramming #JavaDeveloper #100DaysOfCode #ProblemSolving #CodingChallenge #DataStructuresAndAlgorithms #ProgrammingJourney #TechLearning #AlgorithmDesign
To view or add a comment, sign in
-
-
🚀 Day 399 of #500DaysOfCode 🔹 Problem: 129. Sum Root to Leaf Numbers 🔹 Difficulty: Medium 🔹 Language Used: Java ☕ 🧩 Problem Summary: Given the root of a binary tree containing digits (0–9), each root-to-leaf path represents a number. Our task is to find the sum of all numbers formed by these root-to-leaf paths. 💡 Key Idea: We can use Depth-First Search (DFS) to traverse the tree. As we go deeper, we build the current number by multiplying by 10 and adding the current node’s value. When we reach a leaf node, we add that full number to our total sum. ⚙️ Approach: 1️⃣ Start DFS from the root with currentSum = 0. 2️⃣ At each step, update currentSum = currentSum * 10 + node.val. 3️⃣ When reaching a leaf node, return that number. 4️⃣ Combine left and right subtree results to get the total sum. ✅ Example: Input: root = [1,2,3] Output: 25 Paths: 12 + 13 = 25 📘 Lesson Learned: Sometimes, problems that seem about “trees” are really about number construction — a great reminder that recursion can elegantly combine logic with mathematics 🌱 #Day399 #Java #LeetCode #BinaryTree #DFS #ProblemSolving #CodingChallenge #LearnEveryday #Programming #Developer #500DaysOfCode
To view or add a comment, sign in
-
-
#Day-71) Daily LeetCode – Problem #1513: Number of Substrings With Only 1s Just solved a neat binary string problem that blends math with string manipulation. Here's the challenge: 🧩 Problem: Given a binary string s, count all substrings made of only '1's. Return the result modulo 109+710^9 + 7. 📥 Input: "0110111" 📤 Output: 9 📌 Explanation: Substrings like "1", "11", "111"… all count! 💡 My Java Approach: Track consecutive '1's using a counter For each streak, use the formula n(n+1)2\frac{n(n+1)}{2} to count substrings Apply modulo to handle large results 🔍 Why it matters: This problem highlights how simple math tricks (like prefix sums or substring formulas) can drastically reduce brute-force overhead. 🧠 Always open to feedback or alternate strategies—let’s grow together! #LeetCode #Java #DSA #BinaryStrings #ProblemSolving #CodingInPublic #TechJourney
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
-
-
🔢 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
To view or add a comment, sign in
-
-
🔥 LeetCode Day--- 4 | “Median of Two Sorted Arrays” (Hard, Java) Today’s challenge was one of those that really test your logic, patience, and understanding of binary search. This problem wasn’t about just merging two sorted arrays — it was about thinking smarter 🧠. Instead of brute-forcing through both arrays (O(m+n)), I implemented a binary partition approach to achieve O(log(min(m, n))) efficiency 💡 What I learned today: Always choose the smaller array for binary search — it makes the partition logic simpler. Handle boundaries carefully with Integer.MIN_VALUE and Integer.MAX_VALUE. The goal is to find the perfect partition where: Left half ≤ Right half Elements are balanced across both arrays Once that’s done → median can be easily calculated! ✅ Result: Accepted | Runtime: 0 ms 🚀 Hard problem turned into a logic puzzle that was actually fun to solve! 🧩 Concepts Strengthened: Binary Search Partitioning Logic Edge Case Handling Mathematical Thinking #LeetCode #Day4 #Java #BinarySearch #ProblemSolving #CodingChallenge #DataStructures #Algorithms #CodeEveryday #DeveloperJourney #TechLearning #LeetCodeHard #CodingCommunity
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #111 — Minimum Depth of Binary Tree 📘 Problem: Given the root of a binary tree, find its minimum depth — the shortest path from the root node down to the nearest leaf node. A leaf node is one that has no children. Example: Input → [3,9,20,null,null,15,7] Output → 2 Explanation → The shortest path is 3 → 20 → 7. 🧠 My Approach: I used a simple recursive DFS approach to calculate the minimum depth. 1️⃣ If the node is null, return 0. 2️⃣ Recursively find the left and right subtree depths. 3️⃣ If one of the subtrees is missing, return the depth of the existing one. 4️⃣ Otherwise, return the smaller of the two depths + 1. 💡 What I Learned: ✅ The difference between height and depth in trees ✅ How to handle null nodes properly in recursion ✅ The importance of handling edge cases when one subtree is missing 💻 Language Used: Java 🔍 Approach Type: Recursive DFS #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
🌟 Day 73 of 100 Days of Challenge 🌟 📌 LeetCode 220 — Contains Duplicate III Difficulty: 🟥 Hard | Language: Java ☕ Today’s problem was a tricky combination of index range and value range checks. The task was to determine if there exists a pair (i, j) such that: i ≠ j |i - j| ≤ indexDiff |nums[i] - nums[j]| ≤ valueDiff 🧠 Key Insight Instead of brute force (which is O(n²) ❌), we can use a sliding window + TreeSet approach: Maintain a window of size indexDiff. For each nums[i], find if there’s a number within [nums[i] - valueDiff, nums[i] + valueDiff]. TreeSet’s ceiling() function helps in efficient range searching. Slide the window forward by removing older elements. ⏱ Time Complexity: O(n log k) 💾 Space Complexity: O(k) where k = indexDiff ✨ Takeaway: This problem beautifully combines data structures (TreeSet) with sliding window, making it a great practice for hard-level problems. It sharpened my ability to handle both value-based and index-based constraints efficiently. #100DaysOfCode #Day71 #DSA #LeetCode #Java #ProblemSolving #TreeSet #SlidingWindow #CodingChallenge #HardProblem #LearningEveryday
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
Nice