🌸 Day 26 of #100DaysOfCode – LeetCode Problem #605: Can Place Flowers 🧩 Problem: You have a flowerbed represented as an array of 0s and 1s. 0 means empty, 1 means a flower is already planted. Flowers cannot be planted in adjacent plots. Given n, can you plant n new flowers without violating the rule? 💡 Approach: Iterate through the array. For each empty plot, check if its neighbors are empty (or it's on the boundary). If safe, plant a flower and decrease n. If n reaches 0, return true; otherwise, false. 💻 Java Code: class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { for (int i = 0; i < flowerbed.length; i++) { if (flowerbed[i] == 0) { boolean emptyLeft = (i == 0) || (flowerbed[i-1] == 0); boolean emptyRight = (i == flowerbed.length - 1) || (flowerbed[i+1] == 0); if (emptyLeft && emptyRight) { flowerbed[i] = 1; n--; if (n == 0) return true; } } } return n <= 0; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) This problem is a neat reminder that sometimes, simple greedy checks beat complicated algorithms.
Can Place Flowers: A Simple Greedy Solution
More Relevant Posts
-
🚀 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 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 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 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 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 29 of #100DaysOfCode – LeetCode Problem #643: Maximum Average Subarray I 🧩 Problem: Given an integer array nums and an integer k, find the contiguous subarray of length k that has the maximum average value. 💡 Approach: This problem is a great example of the Sliding Window Technique 🪟 Calculate the sum of the first k elements. Then slide the window by one element at a time — subtract the element that goes out, add the new one coming in. Keep track of the maximum sum seen. Return the maximum average (maxSum / k). 💻 Java Code: class Solution { public double findMaxAverage(int[] nums, int k) { double sum = 0; for (int i = 0; i < k; i++) { sum += nums[i]; } double max = sum; for (int i = k; i < nums.length; i++) { sum += nums[i] - nums[i - k]; max = Math.max(max, sum); } return max / k; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) This one reinforces how sliding window optimizations can drastically simplify what looks like a brute-force problem!
To view or add a comment, sign in
-
🚀 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.
To view or add a comment, sign in
-
🚀 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 47 of #100DaysOfCode – LeetCode Problem #1013: Partition Array Into Three Parts With Equal Sum 💬 Problem Summary: Given an array of integers, determine whether it can be split into three non-empty parts such that: Each part has the same sum, and The partitions appear in order (left → mid → right). Formally, we need to find indices i + 1 < j such that: sum(arr[0..i]) == sum(arr[i+1..j-1]) == sum(arr[j..end]) 🧩 Examples: Input: [0,2,1,-6,6,-7,9,1,2,0,1] Output: true ✔️ Three parts sum to 3 each. Input: [0,2,1,-6,6,7,9,-1,2,0,1] Output: false 🧠 Logic: This challenge focuses on finding equal prefix sums: 1️⃣ Compute total sum of the array. 2️⃣ If total sum is not divisible by 3 → ❌ impossible. 3️⃣ Walk through the array, accumulating values. 4️⃣ Each time a segment equals target = totalSum / 3, increase the partition count. 5️⃣ If we find 2 such partitions before the last index → array can be divided. 💻 Java Solution: class Solution { public boolean canThreePartsEqualSum(int[] arr) { int total = 0; for(int num : arr) total += num; if(total % 3 != 0) return false; int target = total / 3; int sum = 0, count = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; if(sum == target) { count++; sum = 0; if(count == 2 && i < arr.length - 1) return true; } } return false; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: A great pattern-recognition problem—once you realize that only two valid partitions are needed (the third is implied), the solution becomes clean and efficient.
To view or add a comment, sign in
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗕𝗶𝗻𝗮𝗿𝘆 𝗦𝗲𝗮𝗿𝗰𝗵: Instead of scanning every element one by one, 𝗯𝗶𝗻𝗮𝗿𝘆 𝘀𝗲𝗮𝗿𝗰𝗵 starts in the middle of a sorted array and keeps narrowing the range by half — cutting the problem size down exponentially until it finds the target (or proves it’s not there). • ⏱️ Time Complexity: O(log n) • ⚙️ Rule #1: Works only on sorted data Here’s a quick Java snippet 👇 public class BinarySearchExample { public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; // Not found } public static void main(String[] args) { int[] numbers = {1, 3, 5, 7, 9, 11}; int index = binarySearch(numbers, 7); System.out.println("Element found at index: " + index); } }
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