JSFiddle - React, Tailwind, and code Playground

by Saurabh Khemka

HTML

You are given an array of integers which was previously sorted but has since been rotated (to left or right) an unknown number of times. Given a number find if it exists in the array.
6, 7 , 9, 2, 4, 5 - 
4 exists 
1 does not

JavaScript

let arr = [6, 7, 9, 2, 4, 5]

function findElement(arr, k) {
  let res = [];
  let j = 0;
  for (let i = 0; i < arr.length; i++) {

    if (!isNaN(arr[i + 1] - arr[j])) {
      if (arr[i + 1] - arr[j] < 0) {
        res.push(arr.slice(j, i + 1))
        j = i + 1;
      }
    } else {
      if (arr[i + 1] === undefined) {
        res.push(arr.slice(j, i + 1))
      }
    }
  }

  console.log(res)

  let result = false;

  for (let i = 0; i < res.length; i++) {
    for (let j = 0; j < res[i].length; j++) {

      if (res[i][0] < k && res[i][res[i].length - 1] > k) {
        result = res[i].indexOf(k) > -1
      }
    }
  }
  return result;
}




console.log(findElement(arr, 4))