In this post, we will see the solution of the Python Coding Question which is already asked in the TCS NQT Exam.
Problem Statement: Given an integer array Arr of size S the task is to find the count of elements whose value is greater than all of its left-hand elements.
Note: 1st element of the array should be considered in the count of the result.
For example:
Arr[]={70,40,80,20,90}
As 70 is the first element, it will consider in the result.
80 and 90 are also the elements that are greater than all of its left hand elements.
Since total of 3 elements is present in the array that meets the condition.
Hence the output = 3.
Example 1:
Input:
5 -> Value of S, represents size of Arr
70-> Value of Arr[0]
40 -> Value of Arr[1]
80-> Value of Arr[2]
20-> Value of Arr[3]
90-> Value of Arr[4]
Output :
3
Example 2:
5 -> Value of S, represents size of Arr
30 -> Value of Arr[0]
40 -> Value of Arr[1]
50 -> Value of Arr[2]
80 -> Value of Arr[3]
90 -> Value of Arr[4]
Output:
5
Constraints:
1<=S<=20
1<=Arr[i]<=10000
Solution:
# taking inputs
S = int(input())
Arr = list(map(int,input().strip().split()))
# initialize the value
max_value = 0
count_element = 0
# iterate through each element from the Arr
for element in Arr:
# check for max if condition satisfied
# then update the max value
# and increment the count by 1
if element > max_value:
count_element += 1
max_value = element
print("Result:", count_element)
Output:
5 70 40 80 20 90 Result: 3
Time complexity: O(N)
Space complexity: O(1)