Sort Array with Two Different Types of Integer Numbers
Sort Array with Two Different Types of Integer Numbers
Description:
Given an array containing only two different types of integer numbers, sort the array in O(n) time complexity without using any inbuilt methods.
Example 1:
Input: arr = = [0, 1, 0, 1, 1, 0]
Output: [0, 0, 0, 1, 1, 1]
Explanation: The array is sorted with all 0’s followed by all 1’s.
Example 2:
Input: arr = [2, 6, 2, 6, 2, 6]
Output: [2, 2, 2, 6, 6, 6]
Explanation: The array is sorted with all 2’s followed by all 6’s.
Example 3:
Input: arr = [1, 0, 1, 0, 1, 0]
Output: [0, 0, 1, 1, 1, 1]
Explanation: The array is sorted with all 0’s followed by all 1’s.
Example 4:
Input: arr = [1, 2, 2, 1, 2, 1]
Output: [1, 1, 1, 2, 2, 2]
Explanation: The array is sorted with all 1’s followed by all 2’s.
Constraints:
The array length |arr| is at least 1 and at most 10^5. Elements in the array are either 0 or 1.
Java Code:
public class HackerAlgo { public static void sortTwoTypes(int[] arr) { int count0 = 0; int count1 = 0; int n = arr.length; // Count the occurrences of 0 and 1 for (int num : arr) { if (num == 0) { count0++; } else if (num == 1) { count1++; } } // Update the array with sorted values for (int i = 0; i< n; i++) { if (i< count0) { arr[i] = 0; } else { arr[i] = 1; } } } public static void main(String[] args) { int[] exampleArr = {0, 1, 0, 1, 1, 0}; sortTwoTypes(exampleArr); System.out.println(Arrays.toString(exampleArr
Python Code:
def sort_two_types(arr): count0 = arr.count(0) count1 = arr.count(1) # Update the array with sorted values arr[:count0] = [0] * count0 arr[count0:] = [1] * count1 # Example usage example_arr = [0, 1, 0, 1, 1, 0] sort_two_types(example_arr) print(example_arr)
C++ Code:
#include <iostream> #include <vector> class HackerAlgo { public: static void sortTwoTypes(std::vector<int>&arr) { int count0 = std::count(arr.begin(), arr.end(), 0); int count1 = std::count(arr.begin(), arr.end(), 1); // Update the array with sorted values std::fill(arr.begin(), arr.begin() + count0, 0); std::fill(arr.begin() + count0, arr.end(), 1); } }; int main() { // Example usage std::vector<int>exampleArr = {0, 1, 0, 1, 1, 0}; HackerAlgo::sortTwoTypes(exampleArr); for (int num :exampleArr) { std::cout<<num<< " "; } std::cout<< std::endl; return 0
JavaScript Code:
class HackerAlgo { static sortTwoTypes(arr) { const count0 = arr.filter(num =>num === 0).length; const count1 = arr.filter(num =>num === 1).length; // Update the array with sorted values arr.fill(0, 0, count0); arr.fill(1, count0); } } // Example usage constexampleArr = [0, 1, 0, 1, 1, 0]; HackerAlgo.sortTwoTypes(exampleArr); console.log(exampleArr);