🚀 Day 38 of #100DaysOfCode – LeetCode Problem #747: Largest Number At Least Twice of Others 💡 Problem Summary: Given an integer array nums, find whether the largest number is at least twice as large as all other numbers. If it is, return the index of the largest element; otherwise, return -1. 📘 Example: Input: nums = [3,6,1,0] Output: 1 Input: nums = [1,2,3,4] Output: -1 🧠 Approach: Find the largest and second largest numbers in the array. If largest >= 2 * secondLargest, return the index of the largest. Otherwise, return -1. 💻 Java Solution: class Solution { public int dominantIndex(int[] nums) { int max = -1, second = -1, index = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { second = max; max = nums[i]; index = i; } else if (nums[i] > second) { second = nums[i]; } } return second * 2 <= max ? index : -1; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: Sometimes, solving problems isn’t about complex algorithms — it’s about thinking clearly and tracking key elements efficiently.
How to find the largest number in an array that is at least twice as large as others
More Relevant Posts
-
🚀 Day 34 of #100DaysOfCode – LeetCode Problem #228: Summary Ranges 🧩 Problem: Given a sorted, unique integer array nums, return the smallest list of ranges that covers all numbers in the array exactly. Each range is represented as: "a->b" if the range covers more than one number. "a" if it covers a single number. 📘 Example: Input: nums = [0,1,2,4,5,7] Output: ["0->2", "4->5", "7"] 💡 Approach: We traverse the array while tracking the start of each range. Whenever we detect a break (i.e., the next number isn’t consecutive), we close the range and store it. 🔍 Steps: Initialize start = nums[0]. Traverse the array. If the next element isn’t consecutive, push "start->current" (or "start" if equal). Move to the next starting number and continue. 💻 Java Code: class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length == 0) return result; int i = 0; while (i < nums.length) { int start = nums[i]; int j = i; while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) { j++; } if (start == nums[j]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[j]); } i = j + 1; } return result; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 3 ms) It’s a simple yet elegant problem — a great reminder that clean logic often beats complex tricks
To view or add a comment, sign in
-
🚀 Day 40 of #100DaysOfCode – LeetCode Problem #905: Sort Array By Parity 💡 Problem Summary: Given an integer array nums, move all even numbers to the front and all odd numbers to the back — return any valid ordering that satisfies this rule. 📘 Examples: Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: Other valid answers include [4,2,3,1], [2,4,1,3]. 🧠 Approach: Create a new list to store results. First, add all even numbers. Then, add all odd numbers. Convert the list back to an array and return it. 💻 Java Solution: class Solution { public int[] sortArrayByParity(int[] nums) { List<Integer> arr = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) arr.add(num); } for (int num : nums) { if (num % 2 != 0) arr.add(num); } int[] array = new int[arr.size()]; for (int i = 0; i < arr.size(); i++) { array[i] = arr.get(i); } return array; } } ⚙️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: Sometimes, a problem doesn’t need a complex algorithm — just logical iteration and clean organization of data. Simple can still be powerful.
To view or add a comment, sign in
-
🚀 Day 42 of #100DaysOfCode – LeetCode Problem #1356: Sort Integers by The Number of 1 Bits 💬 Problem Summary: Given an integer array arr, sort the integers in ascending order by the number of 1’s in their binary representation. If two or more integers have the same number of 1’s, sort them in ascending numerical order. 🧩 Example: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explanation: 0 -> 0 bits 1,2,4,8 -> 1 bit 3,5,6 -> 2 bits 7 -> 3 bits 🧠 Logic: ✅ Count the number of 1s in each number’s binary form. ✅ Sort by (1) number of 1s, then (2) value. 💡 Key trick: Use the bit manipulation technique num &= (num - 1) to count set bits efficiently. 💻 Java Solution: class Solution { public int[] sortByBits(int[] arr) { Arrays.sort(arr, (a, b) -> { int countA = countBits(a); int countB = countBits(b); if (countA == countB) return a - b; return countA - countB; }); return arr; } private int countBits(int num) { int count = 0; while (num > 0) { num &= (num - 1); count++; } return count; } } ⚙️ Complexity: Time: O(n log n) (due to sorting) Space: O(1) ✅ Result: Accepted (Runtime: 1 ms) 💬 Takeaway: This problem beautifully combines sorting logic with bitwise manipulation. It’s a reminder that knowing how data is represented at the binary level gives you powerful optimization tools
To view or add a comment, sign in
-
🚀 Day 31 of #100DaysOfCode – LeetCode Problem #704: Binary Search 🧩 Problem: Given a sorted array and a target value, find the index of the target using an algorithm with O(log n) time complexity. If the target doesn’t exist, return -1. 💡 Approach: This is a classic Binary Search problem. We use two pointers (i and j) to represent the current search range. Calculate the middle index mid. If nums[mid] equals the target → return mid. If target > nums[mid] → search the right half. Else → search the left half. Repeat until the range is empty. 💻 Java Code: class Solution { public int search(int[] nums, int target) { int i = 0, j = nums.length - 1; while (i <= j) { int mid_i = i + (j - i) / 2; int mid_val = nums[mid_i]; if (target < mid_val) { j = mid_i - 1; } else if (target > mid_val) { i = mid_i + 1; } else { return mid_i; } } return -1; } } ⏱️ Complexity: Time: O(log n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) Binary Search — simple, efficient, and one of the most fundamental algorithms every developer must master.
To view or add a comment, sign in
-
🚀 Day 32 of #100DaysOfCode – LeetCode Problem #697: Degree of an Array 🧩 Problem: Given a non-empty array of non-negative integers, the degree of the array is the maximum frequency of any element. The goal is to find the smallest possible length of a contiguous subarray that has the same degree as the entire array. 💡 Approach: To solve this efficiently: Track the first and last occurrence of each element. Track their frequency count. Identify elements that contribute to the array’s maximum degree. For each of those elements, compute the subarray length = last[i] - first[i] + 1. Return the minimum of those lengths. 💻 Java Code: class Solution { public int findShortestSubArray(int[] nums) { Map<Integer, Integer> count = new HashMap<>(); Map<Integer, Integer> first = new HashMap<>(); int degree = 0, bestLen = nums.length; for (int i = 0; i < nums.length; i++) { int num = nums[i]; first.putIfAbsent(num, i); count.put(num, count.getOrDefault(num, 0) + 1); degree = Math.max(degree, count.get(num)); } for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (count.get(num) == degree) { int len = i - first.get(num) + 1; bestLen = Math.min(bestLen, len); } } return bestLen; } } ⏱️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) This problem beautifully blends hashmaps and frequency analysis to derive insights efficiently — a perfect example of thinking beyond brute force!
To view or add a comment, sign in
-
Day 27 of #100DaysOfCode – LeetCode Problem #496: Next Greater Element I 🧩 Problem: Given two arrays nums1 and nums2, where nums1 is a subset of nums2, find the next greater element for each element of nums1 in nums2. If no greater element exists, return -1. 💡 Approach: Use a stack to track the next greater element for all numbers in nums2. Store results in a map for O(1) lookup when iterating nums1. This gives an efficient O(n) solution. 💻 Java Code: class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> mpp = new HashMap<>(); Stack<Integer> st = new Stack<>(); for (int num : nums2) { while (!st.isEmpty() && st.peek() < num) { mpp.put(st.pop(), num); } st.push(num); } while (!st.isEmpty()) mpp.put(st.pop(), -1); int[] ans = new int[nums1.length]; for (int i = 0; i < nums1.length; i++) ans[i] = mpp.get(nums1[i]); return ans; } } ⏱️ Complexity: Time: O(nums1.length + nums2.length) Space: O(nums2.length) ✅ Result: Accepted (Runtime: 0 ms) This problem highlights how monotonic stacks can efficiently solve next-greater-element scenarios without nested loops.
To view or add a comment, sign in
-
🚀 Day 41 of #100DaysOfCode – LeetCode Problem #1332: Remove Palindromic Subsequences 💬 Problem Summary: You’re given a string s consisting only of 'a' and 'b'. In one step, you can remove any palindromic subsequence from s. You need to find the minimum number of steps to make the string empty. 🧩 Example: Input: s = "ababa" Output: 1 Explanation: The entire string is already a palindrome, so remove it in one step. Input: s = "abb" Output: 2 Explanation: Remove "bb" → "a" → "" (2 steps) 🧠 Logic: ✅ If the string is already a palindrome → 1 step. ✅ Otherwise → remove all 'a's in one step and all 'b's in another → 2 steps. 💡 Key Insight: Since the string only contains 'a' and 'b', it will never take more than 2 moves. 💻 Java Solution: class Solution { public int removePalindromeSub(String s) { if (isPalindrome(s)) return 1; return 2; } public boolean isPalindrome(String s) { int i = 0, j = s.length() - 1; while (i < j) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: Sometimes, a problem seems complicated until you spot the pattern — here, limiting characters to 'a' and 'b' turns a potential recursion problem into a simple mathematical observation.
To view or add a comment, sign in
-
🚀 Day 30 of #100DaysOfCode – LeetCode Problem #88: Merge Sorted Array 🧩 Problem: You’re given two sorted arrays, nums1 and nums2, and need to merge them into a single sorted array — in-place inside nums1. The catch? You can’t return a new array, and nums1 already contains extra space for nums2. 💡 Approach: To avoid overwriting elements in nums1, we use a three-pointer approach: Start from the end of both arrays. Compare the elements and place the larger one at the back (nums1[pMerge]). Move pointers accordingly until all elements are merged. 💻 Java Code: class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m - 1, p2 = n - 1, pMerge = m + n - 1; while (p2 >= 0) { if (p1 >= 0 && nums1[p1] > nums2[p2]) { nums1[pMerge--] = nums1[p1--]; } else { nums1[pMerge--] = nums2[p2--]; } } } } ⏱️ Complexity: Time: O(m + n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) A simple yet elegant example of solving array problems in-place using smart pointer manipulation!
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
-
-
💡 LeetCode 3110 – Score of a String 💡 Today, I solved LeetCode Problem #3110: Score of a String, a neat little challenge that emphasizes understanding of ASCII values and absolute differences in Java strings. 🔠✨ 🧩 Problem Overview: You’re given a string s. The score of the string is defined as the sum of the absolute differences between the ASCII values of consecutive characters. Return the total score. 👉 Example: Input → "hello" Output → 13 Explanation → |'e'-'h'| + |'l'-'e'| + |'l'-'l'| + |'o'-'l'| = 3 + 7 + 0 + 3 = 13 💡 Approach: 1️⃣ Initialize a variable sum to store the total score. 2️⃣ Traverse the string from index 1 to end. 3️⃣ For each pair of consecutive characters, find their ASCII difference using Math.abs(). 4️⃣ Add the difference to sum and return it. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the string. ✅ Space Complexity: O(1) — Constant extra space. ✨ Key Takeaways: Strengthened understanding of character encoding and ASCII values. Reinforced clean looping logic and mathematical precision in Java. A great example of how simplicity can elegantly solve a real problem. 🌱 Reflection: Even the smallest coding challenges help sharpen attention to detail — from understanding data types to leveraging built-in functions effectively. Consistency is what transforms learning into mastery. 🚀 #LeetCode #3110 #Java #StringManipulation #ASCII #ProblemSolving #DSA #CodingJourney #CleanCode #AlgorithmicThinking #ConsistencyIsKey
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