Day 40 of #100daysOfCode Problem: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 Difficulty: Medium Language: Java Status: Solved Problem Summary: You're given an array of positive integers nums. In one operation, you can choose an index i (where 0 ≤ i < n - 1) and replace either nums[i] or nums[i+1] with gcd(nums[i], nums[i+1]). You need to find the minimum number of operations to make all elements equal to 1. If it’s not possible, return -1. Key Insight: If there’s at least one 1 in the array → we can convert all other elements to 1 in n - count(1) operations. Otherwise, find the shortest subarray whose GCD = 1. Once found, it takes (j - i) operations to create one 1 and (n - 1) more to make the entire array 1. Algorithm Steps: Count how many elements are 1. If any exist → answer = n - ones. If not → iterate all subarrays, compute GCD until it becomes 1. Keep track of the smallest subarray length that reaches GCD = 1. If none found → return -1. Else return minLength + (n - 1). Time Complexity: O(n² * log(max(nums[i]))) Space Complexity: O(1) Learning Takeaway: Classic GCD reduction logic—search for minimal segment that can “spread” ones across the array. Efficiently reuses math logic in algorithmic reasoning. #Day40 #100DaysOfCode #LeetCode #Math #GCD #Greedy #Java #Algorithms #CodingChallenge #ProblemSolving #DSA
Solved #100DaysOfCode problem 2654 in Java with GCD logic
More Relevant Posts
-
Day 37 of #100daysOfCode — Count Operations to Obtain Zero Problem: 2169. Count Operations to Obtain Zero Difficulty: Easy Language: Java Status: Solved Problem Summary: You’re given two non-negative integers num1 and num2. In each operation: Subtract the smaller number from the larger one. Continue until either number becomes 0. Return the total number of operations. Key Insight: This is essentially a variation of the Euclidean Algorithm for finding GCD, but instead of computing the GCD, we’re counting the total subtractions. By using integer division (n1 / n2) instead of repeatedly subtracting, we can compute the result in O(log n) time. What I Learned: Many iterative subtraction problems can be optimized using division. Recognizing mathematical patterns (like Euclidean GCD) often leads to concise and efficient solutions. #Day37 #100DaysOfCode #LeetCode #DSA #Math #Java #Algorithms #ProblemSolving #CodingChallenge #SoftwareEngineering #LearnByCoding
To view or add a comment, sign in
-
-
💻 Day 44 of my DSA Journey: Searching in a Nearly Sorted Array (Modified Binary Search Approach) 🔍 🔗 The task was to: ✅ Given a nearly sorted array, where each element may be misplaced by at most one position from its correct place, find the index of a given key efficiently. ✅ Use a modified binary search instead of a simple linear search. ✅ Achieve O(log n) time complexity with O(1) extra space. 🔹 Example Usage: int[] arr = {10, 3, 40, 20, 50, 80, 70}; int key = 40; // Output: // Element 40 found at index 2 🔑 Key Learnings: 💡 In a nearly sorted array, an element at index i could be found at: i (its actual position), i - 1 (one place left), or i + 1 (one place right). Hence, instead of checking only mid, we must check mid, mid - 1, and mid + 1. ⚡ Time Complexity: O(log n) ⚡ Space Complexity: O(1) 🌱 Takeaway: This problem strengthened my understanding of binary search adaptations — how slight variations in sorted data can be handled efficiently with small logical tweaks. It’s a great reminder that pattern recognition is key to mastering binary search-based problems 🚀🔥 📌 Hashtags #DSA #Java #BinarySearch #NearlySortedArray #ProblemSolving #CodingJourney #100DaysOfCode #Day414#InterviewPreparation
To view or add a comment, sign in
-
-
💡 LeetCode 2859 – Sum of Values at Indices With K Set Bits 💡 Today, I solved LeetCode Problem #2859, a clever mix of bit manipulation and array traversal that emphasizes how understanding binary representations can simplify computational logic. ⚙️ 🧩 Problem Overview: You are given a list of integers nums and an integer k. Your task is to find the sum of all elements at indices whose binary representation contains exactly k set bits (1s). 👉 Examples: Input → nums = [5,10,1,5,2], k = 1 → Output → 13 (Indices 1 and 2 have one set bit → nums[1] + nums[2] = 10 + 3) 💡 Approach: 1️⃣ Loop through all indices in the list. 2️⃣ Use Integer.bitCount(i) to count the number of set bits in the binary representation of each index. 3️⃣ If it equals k, add nums[i] to the sum. 4️⃣ Return the final total. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Linear scan of the list. ✅ Space Complexity: O(1) — Constant space usage. ✨ Key Takeaways: Strengthened understanding of bit-level operations using Java’s built-in methods. Reinforced how binary logic often leads to elegant and concise solutions. Demonstrated the power of combining mathematical reasoning with simple iteration. 🌱 Reflection: Bit manipulation is one of the most underrated yet powerful tools in problem-solving. This problem shows how thinking in binary can make complex conditions crystal clear — and the solution clean, efficient, and elegant. 🚀 #LeetCode #2859 #Java #BitManipulation #DSA #ProblemSolving #CodingJourney #AlgorithmicThinking #CleanCode #DailyPractice #ConsistencyIsKey
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟏𝟏 𝐨𝐟 #50DaysOfDSA Problem: [𝟑𝟑𝟏𝟖. 𝐅𝐢𝐧𝐝 𝐗-𝐒𝐮𝐦 𝐨𝐟 𝐀𝐥𝐥 𝐊-𝐋𝐨𝐧𝐠 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲𝐬 𝐈] 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐋𝐢𝐧𝐤 : https://lnkd.in/gy47HgPN In this problem, we are given an array nums and two integers k and x. We need to find the 𝐗-𝐒𝐮𝐦 for every subarray of length k. How the X-Sum works: 1️⃣ Count how many times each element appears in the subarray. 2️⃣ Keep only the top x most frequent elements if two have the same frequency, the larger element is prioritized. 3️⃣ Sum up all occurrences of those selected elements to get the X-Sum. If the subarray has less than x distinct elements, just take the sum of all its elements. Key learning: This problem beautifully combines HashMap for frequency counting and PriorityQueue (Min Heap) for selecting the top x elements efficiently. It also strengthens understanding of sliding window logic and priority-based data selection in Java. Here’s a quick breakdown from my solution: Used HashMap to store frequency of elements in each subarray Created a custom Pair class and used PriorityQueue to sort by frequency (and element value when frequencies matched) Extracted top x and calculated their contribution to the subarray sum Every day of this challenge helps reinforce logical thinking and pattern recognition — step by step toward stronger DSA foundations! #50DaysOfDSA #LeetCode #Java #ProblemSolving #CodingChallenge #DSA #DataStructures #Algorithms #WomenInTech #KeepLearning #Consistency
To view or add a comment, sign in
-
-
💻 Day 75 of #100DaysOfCodingChallenge ✨ Problem: 560. Subarray Sum Equals K 📚 Category: Array Manipulation | Subarray Problems 💡 Approach: Brute Force 🧠 Language: Java 🔍 Problem Understanding: We’re given an integer array nums and an integer k. We need to count how many subarrays (continuous parts of the array) have a sum equal to k. Example: Input: nums = [1, 2, 3], k = 3 Output: 2 Explanation: [1,2] and [3] are the subarrays with sum 3. 🧠 Brute Force Approach: In the brute-force method, we check every possible subarray using two loops: 1️⃣ Start from each element as a subarray beginning. 2️⃣ Keep adding elements until the end, and check if the sum equals k. 3️⃣ If yes, increment the count. Although it’s not the most optimized, this approach helps build a strong foundation in understanding subarray logic. ⚙️ Complexity: Time Complexity: O(n²) Space Complexity: O(1) 🌱 Learning: This problem taught me how to approach subarray-based questions step-by-step — starting from brute force before moving toward optimized solutions like prefix sums + hashmaps. Building clarity in fundamentals always makes optimization easier later 🚀 #Day75 #100DaysOfCode #LeetCode #Java #ProblemSolving #CodingJourney #WomenInTech #DSA #ArrayManipulation
To view or add a comment, sign in
-
-
𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 𝐃𝐚𝐢𝐥𝐲 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞: 1513. 𝐍𝐮𝐦𝐛𝐞𝐫 𝐨𝐟 𝐒𝐮𝐛𝐬𝐭𝐫𝐢𝐧𝐠𝐬 𝐖𝐢𝐭𝐡 𝐎𝐧𝐥𝐲 1𝐬 Today’s problem was a clean exercise in mathematical pattern recognition within strings — proving that sometimes, counting smartly beats looping endlessly. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: We are given a binary string and need to count the number of substrings consisting entirely of '1's. Since the count can be large, the result is returned modulo 10⁹ + 7. 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: The core insight is recognizing how consecutive '1's form substrings: For a group of k consecutive '1's, the number of valid substrings = k * (k + 1) / 2. Instead of explicitly using this formula, I used a simple iterative approach: Keep a running counter for consecutive '1's. Add that counter to the result whenever we encounter another '1'. Reset the counter on a '0'. This yields an elegant O(n) single-pass solution with constant space. 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n) Space Complexity: O(1) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬: Mathematical series reasoning helps simplify substring problems. Consecutive counting avoids redundant substring generation. Simplicity and pattern recognition often lead to the most optimal logic. A great reminder that not every problem needs complexity — sometimes, it’s all about spotting the sequence. #LeetCode #DSA #Java #ProblemSolving #Algorithms #CodingPractice #LearningJourney #100DaysOfCode #Consistency #BinaryStrings
To view or add a comment, sign in
-
-
📌 Day 8/100 - Search Insert Position (LeetCode 35) 🔹 Problem: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be inserted in order. 🔹 Approach: I used a binary search approach for efficiency 🔍 1️⃣ Start with two pointers — low and high. 2️⃣ Find the mid index and compare nums[mid] with the target. 3️⃣ If target equals nums[mid], return mid. 4️⃣ If target is smaller, move the high pointer left. 5️⃣ If target is greater, move the low pointer right. 6️⃣ When the loop ends, low gives the correct insert position. 🔹 Key Learning: Binary Search saves time — reducing O(n) to O(log n)! Understanding the condition when to move left/right is key. Even simple problems sharpen logical precision and boundary handling. Each problem strengthens the logic muscle 🧠 — one step closer to mastering algorithms! 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
To view or add a comment, sign in
-
-
✅ Day 73 of LeetCode Medium/Hard Edition Today’s challenge was “K Inverse Pairs Array” — an elegant Dynamic Programming problem that combines combinatorics, recurrence optimization, and modular arithmetic ⚡💡 📦 Problem: Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. An inverse pair is [i, j] where 0 ≤ i < j < n and nums[i] > nums[j]. 🔗 Problem Link: https://lnkd.in/eqt3zX_D ✅ My Submission: https://lnkd.in/eX2ZyCCu 💡 Thought Process: This problem generalizes the concept of counting inversions across all permutations of 1..n. The key idea is to express dp[n][k] in terms of previously computed states using prefix-sum logic to reduce time complexity. We use the recurrence: dp[n][k] = dp[n][k - 1] + dp[n - 1][k] - (k >= n ? dp[n - 1][k - n] : 0) This formula cleverly builds on smaller subproblems by considering where the nth element can be inserted in permutations of size n-1. 🎯 Base Cases: dp[n][0] = 1 (sorted array, no inverse pairs) dp[1][k] = 0 for all k > 0 ⚙️ Complexity: ⏱ Time: O(n × k) 💾 Space: O(n × k) 🧩 Key Learnings: Deepened understanding of prefix-sum optimization in DP. Reinforced modular arithmetic handling (MOD = 10⁹ + 7). Learned how combinatorial recurrence can reduce nested loops. Strengthened recursive + memoized DP formulation in Java. #LeetCodeMediumHardEdition #100DaysChallenge #DynamicProgramming #Recursion #Combinatorics #Java #DSA #ProblemSolving #KeepCoding #LearnEveryday
To view or add a comment, sign in
-
-
🔥 Day 23 | LeetCode Challenge – Clone Graph (Problem #133) Today’s problem focused on graph traversal and deep copying, a classic challenge testing the understanding of graph data structures and recursion. 💡 Concept Overview: Given a node from a connected undirected graph, the goal is to create a deep clone — meaning every node and its corresponding neighbors must be copied into a completely new graph without referencing the original nodes. 📘 Approach Used: Utilized Depth-First Search (DFS) and a HashMap to keep track of already cloned nodes. For each node, a clone was created and stored in the map. Recursively cloned all neighbors, ensuring that shared nodes are referenced properly in the new graph. This approach guarantees correct replication while preventing infinite recursion due to cyclic references. ⚙️ Algorithm Used: Depth-First Search (DFS) 🧾 Language: Java ⚡ Runtime: 25 ms (Beats 65.16%) 💾 Memory Usage: 44.06 MB 🧩 Key Insight: When cloning complex structures like graphs, maintaining a visited map is essential to handle cyclic dependencies efficiently and avoid redundant computations. #Day23 #LeetCode #CloneGraph #GraphTheory #DepthFirstSearch #JavaDeveloper #ProblemSolving #100DaysOfCode #DataStructuresAndAlgorithms #CodingChallenge #ProgrammingJourney #TechLearning #InterviewPreparation
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