LeetCode: Check If Array Is Sorted And Rotated Solution

Approach

Count the number of increasing subarray, call this parts

  • if parts > 1: totally false
  • if parts === 0: totally true
  • if parts = 1: check if the last elem of second part lte the first elem of first part

Implementation

1/**
2 * @param {number[]} nums
3 * @return {boolean}
4 */
5var check = function (nums) {
6 const N = nums.length
7 let parts = 0
8 for (let i = 0; i < N - 1; i++) {
9 if (nums[i] > nums[i + 1]) {
10 parts++
11 }
12 }
13 if (parts > 1) {
14 return false
15 }
16 return parts === 0 || nums[0] >= nums[N - 1]
17}

Comments

Loading comments...

Tags

leetcode

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Duplicate Zeros

Previous Post

HoningJS

Search Posts