OA| OFF Campus Drive
Anonymous User
467
Sep 21, 2021
Sep 21, 2021

Question -
Given an array of size N, sort it in such a way that the following conditions are satisfied:

  1. All even numbers must come before all odd numbers
  2. All even numbers that are divisible by 5 must come before the even numbers that are not divisible by 5.
  3. If 2 even numbers are divisible by 5, then the number having a greater value will come first.
  4. If 2 even numbers are not divisble by 5, then the number having a greater index will come first
  5. All odd numbers must come in relative order as they are present in the array.

I came up with the solution of using custom sort to sort the array - main() calls sort(arr, arr + n, comparator)

My solution -

bool comparator(const int &a, const int &b){
	bool result;
	
	// a is even and b is even
	if(a%2 == 0 && b%2 ==0){
		//as per condition (3)
		if(a%5 == 0 && b%5 ==0)
			result = a>b;
			
		//as per cond (2)
		else if(a%5!=0 && b%5 == 0)
			result = false;
			
		//as per cond (2)
		else if(a%5 == 0 && b%5!=0)
			result = true ;
			
		//as per cond (4)
		else
			result = false ;
	}
	
	//a is even and b is odd  - follow condition (1)
	else if(a%2 == 0 && b%2 != 0)
		result = true;
		
	//a is odd and b is even - follow condition (1)
	else if(a%2 !=0 && b%2==0)
		result = false;
		
	//both are odd - follow condition (5)
	else 
		result = false;
		
	return result;
}

This code failed in few hidden test cases. Is there anything wrong with the custom comparator used in in-built sort()? As per my understanding, the comparator(a,b) should return true if a must come before b else return false. Seems like this may not be right. Can someone clarify if any changes are to be made in the comparator or is there any better solution to this problem.

Comments (1)