🚀 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.
Sort Array By Parity with Java Solution
More Relevant Posts
-
🚀 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 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 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 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 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 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
-
🚀 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 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.
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
-
What happens if a subclass method is called from the parent class construtor ? The subclass method gets called (runtime polymorphism), but it may behave unexpectedly because the subclass object isn’t fully initialized yet. We have Test.java, Child.java, and Parent.java. All of these files are placed in the same package named demo. The following is the code for these files. // Test.java package demo; class Test { public static void main(String[] args) { new Child(); } } // Child.java package demo; class Child extends Parent { int x = 10; Child() { System.out.println("Child constructor executed"); } void show() { System.out.println("Child show executed x = "+x); } } // Parent.java package demo; class Parent { Parent() { System.out.println("Parent constructor executed"); show(); } void show() { System.out.println("Parent show executed"); } } When we execute the command javac -d . *.java, all the Java source files are compiled, and the resulting .class files — Test.class, Parent.class, and Child.class — are placed inside the demo package. After running the program, the output appears as follows: java Demo.Test output : Parent constructor executed Child show executed x = 0 Child constructor executed Several questions may arise from this output: 1. If the Parent constructor was not explicitly invoked, why did it still execute? This occurs because the compiler implicitly inserts super() as the first statement inside the Child constructor. As a result, the Parent constructor is automatically executed. 2. Why was the Child class’s show() method executed even though the Parent class also defines a show() method? This is due to method overriding. The show() method in the Parent class is overridden in the Child class, and therefore the overridden version in the Child class takes precedence at runtime. 3. show() is a non-static method, so how was it called without explicitly passing any object reference? In non-static context, Java automatically provides the this reference. Thus, when show() is called, it is internally treated as this.show(). Even though it is not visible in the code, the method is still invoked on the current object. 4. Why did the value of x print as 0 instead of 10? At the moment when show() is invoked from the Parent constructor, the Child object has not been fully initialized. Memory is allocated for the entire Child object (including both Parent and Child fields), but the Child fields still hold their default values. Hence, x prints as 0 instead of 10. #Java #OOP #programming #coding #technology
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