Sort Array By Parity with Java Solution

🚀 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

Explore content categories