Skip to content

Instantly share code, notes, and snippets.

@Abiola-Farounbi
Created October 26, 2021 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abiola-Farounbi/69d71545c2df39cc39bd776da2e0f3f1 to your computer and use it in GitHub Desktop.
Save Abiola-Farounbi/69d71545c2df39cc39bd776da2e0f3f1 to your computer and use it in GitHub Desktop.
Grouping Digits - Hackerank Solution
# Given an array of binary digits, 0 and 1, sort the array so that all zeros are at one end and all ones are at the other. Which end does not matter. To sort the array, swap any two adjacent elements. Determine the minimum number of swaps to sort the array.
# Example
# arr = [0, 1, 0, 1]
# With 1 move, switching elements 1 and 2 yields [0, 0, 1, 1], a sorted array
# Function Description
# Complete the function minMoves
# minMoves has the following parameter(s):
# int arr[n]: an array of binary digits
# Returns
# int: the minimum number of moves necessarry
# Constraints
# 1 <= n <= 10^5
# arr[i] is in the set {0, 1}
# Another Example
# arr = [1, 1, 1, 1, 0, 0, 0 0]
# We return 0 because we do not need to swap any elements
def minMoves(arr):
# Write your code here
# Intialize the variables
count1 = 0
# The placement of 0
zero_place = 0
for num in arr:
if num == 1:
count1+=1
if num == 0:
zero_place+=count1
# The number of zero's in the array
count0 = len(arr) - count1
# The number of index placement of zero for swapping in the array
rev_dis = count1 * count0 - dis
return min(dis, rev_dis)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment