Skip to main content

Command Palette

Search for a command to run...

Check if Array Is Sorted and Rotated

Published
1 min read
Check if Array Is Sorted and Rotated
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.

There may be duplicates in the original array.

Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.

LeetCode Problem - 1752

class Solution {
    // This method checks if the array can be sorted by rotating it
    public boolean check(int[] nums) {
        int[] sortedNums = Arrays.copyOf(nums, nums.length); // Copy the original array
        Arrays.sort(sortedNums); // Sort the copied array

        // Iterate over all possible rotations
        for(int i = 1; i <= nums.length; i++) {
            int flag = 0; // Flag to count matches

            // Check if the array matches the sorted array after rotation
            for(int j = 0; j < nums.length; j++) {
                if(nums[j] == sortedNums[(j + i) % nums.length]) {
                    flag++; // Increment flag for each match
                }
            }

            // If all elements match, return true
            if(flag == nums.length) {
                return true;
            }
        }

        return false; // Return false if no valid rotation found
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.