bool arraySortedOrNot(vector<int>&A, int N) {
if(is_sorted(A.begin(),A.end())==true) return true;
return false;
}
Problem of the day
You are given an array ‘A’ of length ‘N’ , determine whether the array is sorted in non-decreasing order or not.
Input:
A = [1, 3, 6, 10]
Output:
True
Explanation: Since array ‘A’ is sorted, therefore output is ‘True’.
The first line of the input contains an integer ‘N’.
The next line will contain ‘N’ space-separated integers.
Output Format:-
The output contains a string 'True' or 'False'.
Note:-
You don’t need to print anything. Just implement the given function.
5
10 20 30 20 40
False
A = [10, 20, 30, 20, 40]
Since array ‘A’ is not sorted, therefore output is ‘False’.
1
1100
True
1 <= N <= 10^5
1 <= A[i] <= 10^9
In a non-decreasing array, adjacent elements are increasing.
Approach:
Algorithm:
O( N ), Where ‘N’ is the array ‘A’ length.
Iterating over an array of length ‘N’ takes O(N) complexity. Hence, the overall time complexity will be O( N ).
O( 1 ).
We are taking O( 1 ) extra space for variables. Hence, the overall space complexity will be O( 1 ).
Interview problems
Very simple in C++ (Check arraySortedOrNot)
bool arraySortedOrNot(vector<int>&A, int N) {
if(is_sorted(A.begin(),A.end())==true) return true;
return false;
}
Interview problems
beginner friendly java solution
public class Solution {
public static boolean arraySortedOrNot(int []A, int N) {
for(int i=1;i<N;i++)
if(A[i-1]>A[i])
return false;
return true;
}
}
Interview problems
Java | 2 Liner | O(n)
Please upvote if its helpful !
public class Solution {
public static boolean arraySortedOrNot(int []A, int N) {
for(int i = 1; i<N;i++) if(A[i-1]>A[i]) return false;
return true;
}
}Interview problems
python
n=len(a)
if(n==1):
return True
for i in range(1,n):
if(a[i]<a[i-1]):
return False
return True
pass
Interview problems
Runtime errror
C++
bool arraySortedOrNot(vector<int>&A, int N) {
if (N <= 1) return true;
if (A[N - 2] > A[N - 1]) return false;
return arraySortedOrNot(A, N - 1);
}
JAVA
public class Solution {
public static boolean arraySortedOrNot(int []A, int N) {
if (N <= 1) return true;
if (A[N - 2] > A[N - 1]) return false;
return arraySortedOrNot(A, N - 1);
}
}
CPP code is working fine but the same code in java is giving runtime error at 11/12th test case. what is the issue ?