Day 58/100 Problem Statement : You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times: Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value. Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1. The gcd of two integers is the greatest common divisor of the two integers. Input: nums = [2,6,3,4] Output: 4 Solution : https://lnkd.in/eaD3v_XT public int minOperations(int[] nums) { int n = nums.length; int ones = 0; for (int x : nums) { if (x == 1) ones++; } if (ones > 0) return n - ones; int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int g = nums[i]; for (int j = i + 1; j < n; j++) { g = gcd(g, nums[j]); if (g == 1) { ans = Math.min(ans, j - i); break; } } } if (ans == Integer.MAX_VALUE) return -1; return ans + n - 1; } private int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
Min Operations to Make All Elements Equal to 1
More Relevant Posts
-
Day 43/100 Problem Statement : Given an array nums, you can perform the following operation any number of times: Select the adjacent pair with the minimum sum in nums. If multiple such pairs exist, choose the leftmost one. Replace the pair with their sum. Return the minimum number of operations needed to make the array non-decreasing. An array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists). Input: nums = [5,2,3,1] Output: 2 Solution : https://lnkd.in/g3Z6NQxN public int minimumPairRemoval(int[] nums) { int length = nums.length - 1; int count = 0; while(length > 0) { boolean increase = true; int minSum = Integer.MAX_VALUE; int minIndex = -1; for(int i = 0; i < length; i++) { if(nums[i] > nums[i + 1]) increase = false; if(nums[i] + nums[i + 1] < minSum) { minSum = nums[i] + nums[i + 1]; minIndex = i; } } if(increase) break; nums[minIndex] = minSum; for(int i = minIndex + 1; i < length; i++) nums[i] = nums[i + 1]; length--; count++; } return count; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
Day 45/100 – #100DaysOfCode 🚀 | #Java #Hashing #SlidingWindow ✅ Problem Solved: Contains Duplicate III (LeetCode 220) 🧩 Problem Summary: Given an integer array and integers k and t, determine if there exist two distinct indices i and j such that: |i - j| ≤ k |nums[i] - nums[j]| ≤ t 💡 Approach Used: Used a Sliding Window + TreeSet to maintain numbers in a sorted structure. Steps: Traverse the array and maintain a window of at most size k. For each element x, find if there exists another element in the set such that |x - y| ≤ t. This is done using ceiling() to find the closest value ≥ x. Insert the element in TreeSet and remove the element that slides out. ⚙️ Time Complexity: O(n log k) 📦 Space Complexity: O(k) ✨ Takeaway: This problem teaches how ordered data structures like TreeSet help efficiently handle range queries in sliding window scenarios. #Java #TreeSet #SlidingWindow #LeetCode #ProblemSolving #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
💡 Day 10 of 100 Days of LeetCode 📘 Problem: #26. Remove Duplicates from Sorted Array 💻 Difficulty: Easy 🔍 Concept: The task is to remove duplicates in-place from a sorted array so that each unique element appears only once. The function should return the count of unique elements k. ⚙️ Approach Used: Used two-pointer technique — one pointer (k) tracks the position of the last unique element, and the other (i) scans the array. Whenever a new unique element is found, it’s moved to the next position in the array. 🧠 Key Learnings: Mastered the in-place modification concept in arrays. Learned how to use two-pointer pattern for linear-time solutions. Refined logic building with minimal extra space usage (O(1) space). 💻 Code (Java): class Solution { public int removeDuplicates(int[] nums) { int k = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[k]) { k++; nums[k] = nums[i]; } } return k + 1; } } 💬 Reflection: A simple-looking problem — but it’s one that trains you to think in space-efficient ways. Sometimes, mastering basics is what builds strong problem-solving intuition! #100DaysOfLeetCode #Day10 #DSA #Java #ProblemSolving #CodingChallenge #LeetCode #LearningEveryday
To view or add a comment, sign in
-
-
Day 50 of #75DaysDSAChallenge Problem: 7. Reverse Integer Difficulty: 🟠 Medium Platform: LeetCode 🧩 Problem Statement Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes it to go outside the signed 32-bit integer range [-2³¹, 2³¹ - 1], return 0. Example: Input: x = 123 Output: 321 💡 Approach 1️⃣ Extract the last digit using x % 10. 2️⃣ Remove the last digit using x / 10. 3️⃣ Add the digit to the reversed number. 4️⃣ Before updating, check for overflow conditions. 5️⃣ Continue until all digits are processed. #LeetCode #Java #DSA #CodingChallenge #75DaysDSAChallenge #ProblemSolving #TechLearning #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 75 — Find All Pairs with a Given Sum (75/100) 🧩 Problem: Given an array of integers, find all unique pairs (a, b) such that a + b = 0. Return all pairs sorted in ascending order based on their first and then second element. 📘 Example: Input: [1, -1, 2, -2, 3] Output: [[-2, 2], [-1, 1]] ⚙️ Approach: Sort the array. Use two-pointer technique (left and right indices). Move pointers based on the sum: If sum == 0 → store the pair. If sum < 0 → move left pointer up. If sum > 0 → move right pointer down. Used a HashSet to avoid duplicates. Finally, sort all pairs lexicographically. 🧠 Key Concept: Efficient pair finding in sorted arrays using two-pointer logic (O(n log n)). ⏱️ Time Complexity: O(n log n) 💾 Space Complexity: O(n) ✅ Result: All 1115 / 1115 test cases passed ✅ Accuracy: 100% Points: 2 / 2 Total Score: 144 💪 Every line of code brings you closer to mastery — stay consistent, stay sharp! 🔥 #100DaysOfDSA #Java #TwoPointer #GeeksForGeeks #DSAChallenge #CodingJourney
To view or add a comment, sign in
-
-
🗓 Day 6 / 100 – #100DaysOfLeetCode 📘 Problem: 3228. Maximum Number of Operations to Move Ones to the End Difficulty: Medium 💡 Problem Summary: Given a binary string s, you can repeatedly choose an index i where s[i] == '1' and s[i+1] == '0', and move that '1' to the right until it reaches the end of the string or hits another '1'. The goal is to find the maximum number of such operations possible. 🧠 My Approach: Instead of simulating the moves (which would be inefficient), I used a counting strategy: Keep a running count of the number of '1's seen so far (cnt). Whenever a '0' appears after one or more '1's, we can perform cnt operations involving those ones. Sum these up for the final result. 📊 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
💻 Day 74 of #LeetCode100DaysChallenge Solved LeetCode 18: 4Sum — a challenging problem that enhances array manipulation, two-pointer technique, and handling duplicates. 🧩 Problem: Given an array nums of n integers and a target value, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: All indices are distinct The sum of the four numbers equals the target Result can be returned in any order 💡 Approach — Sorting + Two Pointers: 1️⃣ Sort the array to simplify duplicate handling. 2️⃣ Use two nested loops to fix the first two numbers. 3️⃣ Apply the two-pointer technique for the remaining two numbers to find quadruplets that sum to the target. 4️⃣ Skip duplicate elements to ensure uniqueness. 5️⃣ Collect all valid quadruplets in a list. ⚙️ Complexity: Time: O(N³) — two loops + two-pointer scan Space: O(N) — for storing results ✨ Key Takeaways: ✅ Strengthened two-pointer technique for k-sum problems. ✅ Learned efficient strategies for avoiding duplicates in combinatorial results. ✅ Practiced breaking down complex problems into smaller, manageable steps. #LeetCode #100DaysOfCode #Java #TwoPointers #Arrays #4Sum #DSA #ProblemSolving #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
💻 Day 65 of #LeetCode100DaysChallenge Solved LeetCode 219: Contains Duplicate II — a smart problem involving hashing and sliding window logic. 🧩 Problem: Given an integer array nums and an integer k, return true if there exist two distinct indices i and j such that: nums[i] == nums[j], and |i - j| <= k. 💡 Approach — HashMap (Index Tracking): 1️⃣ Use a HashMap to store each number and its most recent index. 2️⃣ For every element nums[i]: If it’s already in the map and i - map.get(nums[i]) <= k, return true. Otherwise, update the index in the map. 3️⃣ If no pair found, return false. ⚙️ Complexity: Time: O(N) — single pass through the array. Space: O(N) — for storing indices in the map. ✨ Key Takeaways: ✅ Strengthened understanding of index-based distance checking. ✅ Efficiently applied hash maps for tracking element positions. ✅ Learned how to implement O(N) duplicate checks with window constraints. #LeetCode #100DaysOfCode #Java #HashMap #SlidingWindow #DSA #ProblemSolving #CodingChallenge #WomenInTech
To view or add a comment, sign in
-
-
Hello Connections ✋ 🚀 #Day16 of #Day100 challenge of improving my self in java , SQL, frontend, Git and GitHub. 🥇 Java : - Reverse a String: Input: 'hello' | Output: 'olleh' Check Palindrome: Input: 'radar' | Output: True Find Length: Input: 'hello' | Output: 5. 🥈 SQL : year, month, day, month name, day name tags. ✅ Step 1: Create and Insert Sample Data CREATE TABLE event ( event_id NUMBER, event_name VARCHAR2(100), event_date DATE ); INSERT INTO event VALUES (1, 'Tech Meetup', TO_DATE('2023-11-08', 'YYYY-MM-DD')); INSERT INTO event VALUES (2, 'Hackathon', TO_DATE('2023-12-15', 'YYYY-MM-DD')); INSERT INTO event VALUES (3, 'Workshop', TO_DATE('2024-01-10', 'YYYY-MM-DD')); COMMIT; ✅ Step 2: Extract Year, Month, Day, Month Name, Day Name SELECT event name, event_date, TO_CHAR(event date, 'YYYY') AS year, TO_CHAR(event_date, 'MM') AS month number, TO_CHAR(event date, 'DD') AS day, TO_CHAR(event_date, 'Month') AS month name, TO_CHAR(event_date, 'Day') AS day_name FROM event; 🥉 CSS : text , font, border properties eg : Stylish Profile Card 10000 Coders karunakar pusuluri HCLTech #Strings #textproperties #year #month #day #monthname #dayname #java #sql #css
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