Walmart Coding round

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2023-04-05Added By Anonymous
Source: Link

position - IN3

In one of my coding round i was asked below question. Interviewer were expecting solution with O(n) time complexity with in-place.


The best solution i think is O(n*r) with in-place (used enhance of Dutch National Flag https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/). Please help me to find O(n) solution. is O(n) solution possible with in-place?

where n is Array length

And r is types of unique elements in array


Question -

Given an array nums with 'n' objects of 'r' types , sort them in-place so that objects of the same type are adjacent and are in the order provided. You must solve this problem without using the library's sort function.

1<= n <= 1000

1<= r <=50


Example 1:

Consider a shelf in walmart which has inventory of type bread, chocolate, or chips

r = 3

Rearrange the shelf in the order bread, chocolate, and chips.

We will use the integers 0, 1, and 2 to represent the color bread, chocolate, and chips, respectively.

Input: nums = [2,0,2,1,1,0]

Output: [0,0,1,1,2,2]

Input: nums = [2,0,1]

Output: [0,1,2]


Example 2:

Consider a shelf in walmart which has inventory of type cookie ,gum ,bread, chocolate, and chips

r = 5

Rearrange the shelf in the order gum, cookie, bread, chocolate and chips .

We will use the integers 0, 1, and 2 ,3, 4 to represent gum, cookie, bread, chocolate and chips.

Input: nums = [2,4,3,1,2,4,0,2,1,3,4,2,1]

Output: [0,1,1,1,2,2,2,2,3,3,4,4,4]


Answer with O(n*r)

1void sortWithDutchNationalFlag(int[] nums, int r){ 2 3 int so = 0; 4 int n = nums.length; 5 6 for(int k = r-1 ; k>0 ; k--){ 7 int sb = 0 ; 8 for(int i = 0 ; i< n-so; i++){ 9 10 if(nums[i] == k){ 11 sb++; 12 } 13 14 else if(sb > 0){ 15 nums[i - sb] = nums[i]; 16 nums[i] = k; 17 } 18 } 19 so += sb; 20 } 21}
Comments