Array Game
Arth Agrawal
(22BCE3196)
Problem Statement
Test Cases and Constraints
Example 1:
Input: arr = [2,1,3,5,4,6,7], k = 2
Output: 5
Explanation: Let's see the rounds of the game:
Round | arr | winner | win_count
1 | [2,1,3,5,4,6,7] | 2 | 1
2 | [2,3,5,4,6,7,1] | 3 | 1
3 | [3,5,4,6,7,1,2] | 5 | 1
4 | [5,4,6,7,1,2,3] | 5 | 2
So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
Example 2:
Input: arr = [3,2,1]
k = 10
Output: 3
Explanation: 3 will win the first 10 rounds consecutively.
Example 3:
Input : arr = [6,1,3,7,4,8], k = 3
Output = 8
Explanation: Let's see the rounds of the game:
Round | arr | winner | win_count
1 | [6,1,3,7,4,8] | 6 | 1
2 | [6,3,7,4,8,1] | 6 | 2
3 | [6,7,4,8,1,3] | 7 | 1
4 | [7,4,8,1,3,6] | 7 | 2
5 | [7,8,1,3,6,4] | 8 | 1
6 | [8,1,3,6,4,7] | 8 | 2
7 | [8,3,6,4,7,1] | 8 | 3
Since, 8 has won three consecutive times, the no. 8 is the winner and it is printed.
Question Interpretation
Firstly we compare the first two elements of the given
aray.
The smaller value should be removed from the list and
appended to the end.
We need to count the no. of times every element won.
As soon as any given element wins the game k(inputed
by the user) no. of times that element is the winner and
that element should be printed.
Initial Code Idea(Algorithm)
1. Start
2. Input the array and the value k.
3. Initiate a while loop inside which we will compare the first two elements.
4. The smaller of the elements will be removed from the list and then it will be appended at
the end of the list.
5. Define a variable called win_count(initialised to zero).
6. Count the number of times each element won using win_count
7. If the win_count at any point becomes == k ; then terminate the loop and print that value.
8. End
FlowChart
Initial Code
Redundancy in code
The highlighted area was causing
redundancy in the code.
Due to these extra lines of code, the
time taken for the code to run was
exceeding the given time limit.
Because of this I was getting a Time
Limit Exceeded error
This code can be shortened using list
operations.
Error i was
running into
Final Code
Test case 1: successfull
Test case 2: successfull
all test cases successfull
References