The Wayback Machine - https://web.archive.org/web/20240915121829/https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/
Open In App

Search in a sorted and rotated Array

Last Updated : 05 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a sorted and rotated array arr[] of n distinct elements, the task is to find the index of given key in the array. If the key is not present in the array, return -1.

Example:  

Input  : arr[] = {4, 5, 6, 7, 0, 1, 2}, key = 0
Output : 4

Input  : arr[] = { 4, 5, 6, 7, 0, 1, 2 }, key = 3
Output : -1

Input : arr[] = {50, 10, 20, 30, 40}, key = 10   
Output : 1

Using Linear Search

A simple approach is to iterate through the array and check for each element, if it matches the target then return the index. otherwise, return –1.

Complexity : O(n) time and O(1) auxiliary space

Using Two Binary Searches

1) Find the pivot point (or index of the min element) : For example, the min in {4, 5, 6, 7, 0, 1, 2} is 0 at index 4. And the min in {50, 10, 20, 30, 40} is 10 at index 1. How to find index of min? We have discussed in detail here.

2) Do Binary Search in a Sorted Subarray: Once we find the pivot, we can easily divide the given array into two sorted subarrays using the index of the min. For example {4, 5, 6, 7, 0, 1, 2} as {{4, 5, 6, 7}, {1, 2}} and {50, 10, 20, 30, 40} as {{50}, {10, 20, 30, 40} }. Following are the cases that arise

  • If the given key is same as minimum, we return
  • If min index is 0, then the whole array is sorted, we call binary search for the whole array.
  • Now how do we decide the subarray in other cases. One simple idea can be to call binary search for both sides. This will keep the overall time complexity as O(Log n) only, but we can save one binary search. The idea is to compare the given key with the first element. For example, {{4, 5, 6, 7}, {1, 2}} and the key = 6. If key is greater than equal to the first element, we do binary search in the first subarray else in the second.
C++
#include <bits/stdc++.h>
using namespace std;

// An iterative binary search function.
int binarySearch(vector<int> &arr, int low, int high, int x) {
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == x) return mid;
        if (arr[mid] < x) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

// Function to get pivot. For array 3, 4, 5, 6, 1, 2
// it returns 4 (index of 1)
int findPivot(vector<int> &arr, int low, int high) {
    while (low < high) {
      
        // The current subarray is already sorted,
        // the minimum is at the low index
        if (arr[low] <= arr[high])        
            return low;
        
        int mid = (low + high) / 2;

        // The right half is not sorted. So
        // the minimum element must be in the
        // right half.
        if (arr[mid] > arr[high])
            low = mid + 1;
        // The right half is sorted. Note that in
        // this case, we do not change high to mid - 1
        // but keep it to mid. The mid element
        // itself can be the smallest
        else
            high = mid;
    }

    return low;
}

// Searches an element key in a pivoted
// sorted array arr of size n
int pivotedBinarySearch(vector<int> &arr, int n, int key) {
    int pivot = findPivot(arr, 0, n - 1);

    // If the minimum element is present at index
    // 0, then the whole array is sorted
    if (pivot == 0)
        return binarySearch(arr, 0, n - 1, key);

    // If we found a pivot, then first compare with pivot
    // and then search in two subarrays around pivot
    if (arr[pivot] == key)
        return pivot;

    if (arr[0] <= key)
        return binarySearch(arr, 0, pivot - 1, key);
    return binarySearch(arr, pivot + 1, n - 1, key);
}

// Driver program to check above functions
int main() {
    // Let us search 3 in below array
    vector<int> arr = {5, 6, 7, 8, 9, 10, 1, 2, 3};
    int key = 3;
    cout << pivotedBinarySearch(arr, arr.size(), key);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    // An iterative binary search function.
    public static int binarySearch(int[] arr, int low, int high, int x) {
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) return mid;
            if (arr[mid] < x) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }

    // Function to get pivot. For array 3, 4, 5, 6, 1, 2
    // it returns 4 (index of 1)
    public static int findPivot(int[] arr, int low, int high) {
        while (low < high) {
            // The current subarray is already sorted,
            // the minimum is at the low index
            if (arr[low] <= arr[high])
                return low;
            
            int mid = (low + high) / 2;
            // The right half is not sorted. So
            // the minimum element must be in the
            // right half.
            if (arr[mid] > arr[high])
                low = mid + 1;
            // The right half is sorted. Note that in
            // this case, we do not change high to mid - 1
            // but keep it to mid. The mid element
            // itself can be the smallest
            else
                high = mid;
        }
        return low;
    }

    // Searches an element key in a pivoted
    // sorted array arr of size n
    public static int pivotedBinarySearch(int[] arr, int n, int key) {
        int pivot = findPivot(arr, 0, n - 1);

        // If the minimum element is present at index
        // 0, then the whole array is sorted
        if (pivot == 0)
            return binarySearch(arr, 0, n - 1, key);

        // If we found a pivot, then first compare with pivot
        // and then search in two subarrays around pivot
        if (arr[pivot] == key)
            return pivot;

        if (arr[0] <= key)
            return binarySearch(arr, 0, pivot - 1, key);
        return binarySearch(arr, pivot + 1, n - 1, key);
    }

    // Driver program to check above functions
    public static void main(String[] args) {
        // Let us search 3 in below array
        int[] arr = {5, 6, 7, 8, 9, 10, 1, 2, 3};
        int key = 3;
        System.out.println(pivotedBinarySearch(arr, arr.length, key));
    }
}
Python
def binary_search(arr, low, high, x):
    # An iterative binary search function.
    while low <= high:
        mid = low + (high - low) // 2
        if arr[mid] == x:
            return mid
        if arr[mid] < x:
            low = mid + 1
        else:
            high = mid - 1
    return -1

def find_pivot(arr, low, high):
    # Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 4 (index of 1) 
    while low < high:
        # The current subarray is already sorted, the minimum is at the low index
        if arr[low] <= arr[high]:
            return low
        
        mid = (low + high) // 2
        # The right half is not sorted. So the minimum element must be in the right half.
        if arr[mid] > arr[high]:
            low = mid + 1
        # The right half is sorted. Note that in this case, we do not change high to mid - 1
        # but keep it to mid. The mid element itself can be the smallest
        else:
            high = mid
    return low

def pivoted_binary_search(arr, n, key):
    #Searches an element key in a pivoted sorted array arr of size n 
    pivot = find_pivot(arr, 0, n - 1)

    # If the minimum element is present at index 0, then the whole array is sorted
    if pivot == 0:
        return binary_search(arr, 0, n - 1, key)

    # If we found a pivot, then first compare with pivot and then search in two subarrays around pivot
    if arr[pivot] == key:
        return pivot

    if arr[0] <= key:
        return binary_search(arr, 0, pivot - 1, key)
    return binary_search(arr, pivot + 1, n - 1, key)

# Driver program to check above functions
if __name__ == "__main__":
    # Let us search 3 in below array
    arr = [5, 6, 7, 8, 9, 10, 1, 2, 3]
    key = 3
    print(pivoted_binary_search(arr, len(arr), key))
C#
using System;

class Program {
    // An iterative binary search function.
    static int BinarySearch(int[] arr, int low, int high, int x) {
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) return mid;
            if (arr[mid] < x) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }

    // Function to get pivot. For array 3, 4, 5, 6, 1, 2
    // it returns 4 (index of 1)
    static int FindPivot(int[] arr, int low, int high) {
        while (low < high) {
            // The current subarray is already sorted,
            // the minimum is at the low index
            if (arr[low] <= arr[high])
                return low;
            
            int mid = (low + high) / 2;
            // The right half is not sorted. So
            // the minimum element must be in the
            // right half.
            if (arr[mid] > arr[high])
                low = mid + 1;
            // The right half is sorted. Note that in
            // this case, we do not change high to mid - 1
            // but keep it to mid. The mid element
            // itself can be the smallest
            else
                high = mid;
        }
        return low;
    }

    // Searches an element key in a pivoted
    // sorted array arr of size n
    static int PivotedBinarySearch(int[] arr, int n, int key) {
        int pivot = FindPivot(arr, 0, n - 1);

        // If the minimum element is present at index
        // 0, then the whole array is sorted
        if (pivot == 0)
            return BinarySearch(arr, 0, n - 1, key);

        // If we found a pivot, then first compare with pivot
        // and then search in two subarrays around pivot
        if (arr[pivot] == key)
            return pivot;

        if (arr[0] <= key)
            return BinarySearch(arr, 0, pivot - 1, key);
        return BinarySearch(arr, pivot + 1, n - 1, key);
    }

    // Driver program to check above functions
    static void Main(string[] args) {
        // Let us search 3 in below array
        int[] arr = {5, 6, 7, 8, 9, 10, 1, 2, 3};
        int key = 3;
        Console.WriteLine(PivotedBinarySearch(arr, arr.Length, key));
    }
}
JavaScript
// An iterative binary search function.
function binarySearch(arr, low, high, x) {
    while (low <= high) {
        let mid = low + Math.floor((high - low) / 2);
        if (arr[mid] === x) return mid;
        if (arr[mid] < x) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

// Function to get pivot. For array 3, 4, 5, 6, 1, 2
// it returns 4 (index of 1)
function findPivot(arr, low, high) {
    while (low < high) {
        // The current subarray is already sorted,
        // the minimum is at the low index
        if (arr[low] <= arr[high])
            return low;
        
        let mid = Math.floor((low + high) / 2);
        // The right half is not sorted. So
        // the minimum element must be in the
        // right half.
        if (arr[mid] > arr[high])
            low = mid + 1;
        // The right half is sorted. Note that in
        // this case, we do not change high to mid - 1
        // but keep it to mid. The mid element
        // itself can be the smallest
        else
            high = mid;
    }
    return low;
}

// Searches an element key in a pivoted
// sorted array arr of size n
function pivotedBinarySearch(arr, n, key) {
    let pivot = findPivot(arr, 0, n - 1);

    // If the minimum element is present at index
    // 0, then the whole array is sorted
    if (pivot === 0)
        return binarySearch(arr, 0, n - 1, key);

    // If we found a pivot, then first compare with pivot
    // and then search in two subarrays around pivot
    if (arr[pivot] === key)
        return pivot;

    if (arr[0] <= key)
        return binarySearch(arr, 0, pivot - 1, key);
    return binarySearch(arr, pivot + 1, n - 1, key);
}

// Driver program to check above functions
function main() {
    // Let us search 3 in below array
    const arr = [5, 6, 7, 8, 9, 10, 1, 2, 3];
    const key = 3;
    console.log(pivotedBinarySearch(arr, arr.length, key));
}

main();

Output
8

Using One Binary Search:

The idea is based on the fact that in a sorted and rotated array, if we go to mid, then either the left half would be sorted or the right half (Both can also be sorted if the mid is the minimum or maximum element). For example, n arr[] = {5, 6, 0, 1, 2, 3, 4}, mid = 3 and we can see that the subarray from mid+1 to high is sorted. And in {5, 6, 7, 8, 9, 3, 4}, we can see that the subarray from low to mid-1 is sorted. We can check which half is sorted by comparing arr[low] and arr[mid] (We could also compare arr[high] and arr[mid]).

  • Find the mid point. If key is same as the mid, return the mid.
  • Find which half is sorted. If the key lies in the sorted half, move to that half. Otherwise move to the other half.

Note that once we find which half is sorted, we can easily check if the key lies here by checking if key lies in the range from smallest to largest in this half.

C++
#include <bits/stdc++.h>
using namespace std;

int pivotedSearch(vector<int>& arr, int key) {
  
    // Initialize two pointers, low and high, at the start
    // and end of the array.
    int low = 0, high = arr.size() - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        // Case 1: Find key
        if (arr[mid] == key)
            return mid;

        // Case 2: Left half is sorted
        if (arr[mid] >= arr[low]) {
          
            // If the key lies within this sorted half,
            // move the high pointer to mid - 1.
            if (key >= arr[low] && key < arr[mid])
                high = mid - 1;
          
            // Otherwise, move the low pointer to mid + 1.
            else
                low = mid + 1;
        }
      
        // Case 3: Right half is sorted
        else {
          
            // If the key lies within this sorted half,
            // move the low pointer to mid + 1.
            if (key > arr[mid] && key <= arr[high])
                low = mid + 1;
          
            // Otherwise, move the high pointer to mid - 1.
            else
                high = mid - 1;
        }
    }

    return -1; // Key not found
}

// Driver code
int main() {
    vector<int> arr1 = {4, 5, 6, 7, 0, 1, 2};
    int key1 = 0;
    int result1 = pivotedSearch(arr1, key1);
    cout << result1 << endl; // Output: 4

    vector<int> arr2 = {4, 5, 6, 7, 0, 1, 2};
    int key2 = 3;
    int result2 = pivotedSearch(arr2, key2);
    cout << result2 << endl; // Output: -1

    return 0;
}
Java
import java.util.*;

public class GFG {

    // Search in a pivoted sorted array
    public static int pivotedSearch(List<Integer> arr, int key) {
        int low = 0, high = arr.size() - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;

            // Case 1: Find key
            if (arr.get(mid) == key)
                return mid;

            // Case 2: Left half is sorted
            if (arr.get(mid) >= arr.get(low)) {
                if (key >= arr.get(low) && key < arr.get(mid))
                    high = mid - 1;
                else
                    low = mid + 1;
            }

            // Case 3: Right half is sorted
            else {
                if (key > arr.get(mid) && key <= arr.get(high))
                    low = mid + 1;
                else
                    high = mid - 1;
            }
        }

        return -1; // Key not found
    }

    public static void main(String[] args) {
        List<Integer> arr1 = Arrays.asList(4, 5, 6, 7, 0, 1, 2);
        int key1 = 0;
        int result1 = pivotedSearch(arr1, key1);
        System.out.println(result1); // Output: 4

        List<Integer> arr2 = Arrays.asList(4, 5, 6, 7, 0, 1, 2);
        int key2 = 3;
        int result2 = pivotedSearch(arr2, key2);
        System.out.println(result2); // Output: -1
    }
}
Python
def pivoted_search(arr, key):
    low, high = 0, len(arr) - 1

    while low <= high:
        mid = low + (high - low) // 2

        # Case 1: Find key
        if arr[mid] == key:
            return mid

        # Case 2: Left half is sorted
        if arr[mid] >= arr[low]:
            if key >= arr[low] and key < arr[mid]:
                high = mid - 1
            else:
                low = mid + 1

        # Case 3: Right half is sorted
        else:
            if key > arr[mid] and key <= arr[high]:
                low = mid + 1
            else:
                high = mid - 1

    return -1  # Key not found

# Driver code
arr1 = [4, 5, 6, 7, 0, 1, 2]
key1 = 0
result1 = pivoted_search(arr1, key1)
print(result1)  # Output: 4

arr2 = [4, 5, 6, 7, 0, 1, 2]
key2 = 3
result2 = pivoted_search(arr2, key2)
print(result2)  # Output: -1
C#
using System;
using System.Collections.Generic;

public class GFG {

    // Search in a pivoted sorted array
    public static int PivotedSearch(List<int> arr, int key) {
        int low = 0, high = arr.Count - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;

            // Case 1: Find key
            if (arr[mid] == key)
                return mid;

            // Case 2: Left half is sorted
            if (arr[mid] >= arr[low]) {
                if (key >= arr[low] && key < arr[mid])
                    high = mid - 1;
                else
                    low = mid + 1;
            }

            // Case 3: Right half is sorted
            else {
                if (key > arr[mid] && key <= arr[high])
                    low = mid + 1;
                else
                    high = mid - 1;
            }
        }

        return -1; // Key not found
    }

    public static void Main() {
        List<int> arr1 = new List<int> { 4, 5, 6, 7, 0, 1, 2 };
        int key1 = 0;
        int result1 = PivotedSearch(arr1, key1);
        Console.WriteLine(result1); // Output: 4

        List<int> arr2 = new List<int> { 4, 5, 6, 7, 0, 1, 2 };
        int key2 = 3;
        int result2 = PivotedSearch(arr2, key2);
        Console.WriteLine(result2); // Output: -1
    }
}
JavaScript
function pivotedSearch(arr, key) {
    let low = 0, high = arr.length - 1;

    while (low <= high) {
        let mid = low + Math.floor((high - low) / 2);

        // Case 1: Find key
        if (arr[mid] === key) {
            return mid;
        }

        // Case 2: Left half is sorted
        if (arr[mid] >= arr[low]) {
            if (key >= arr[low] && key < arr[mid]) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }

        // Case 3: Right half is sorted
        else {
            if (key > arr[mid] && key <= arr[high]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
    }

    return -1; // Key not found
}

// Driver code
const arr1 = [4, 5, 6, 7, 0, 1, 2];
const key1 = 0;
const result1 = pivotedSearch(arr1, key1);
console.log(result1); // Output: 4

const arr2 = [4, 5, 6, 7, 0, 1, 2];
const key2 = 3;
const result2 = pivotedSearch(arr2, key2);
console.log(result2); // Output: -1

Output
4
-1

Time Complexity: O(log n)
Auxiliary Space: O(1)




Previous Article
Next Article

Similar Reads

Circularly Sorted Array (Sorted and Rotated Array)
Circularly sorted arrays are arrays that are sorted in ascending or descending order and then rotated by a number of steps. Let us take an example to know more about circularly sorted arrays: Consider an array: arr[] = {23, 34, 45, 12, 17, 19}The elements here, {12, 17, 19, 23, 34, 45} are sorted 'In-order' but they are rotated to the left by 3 tim
7 min read
Search an element in a sorted and rotated array with duplicates
Given an array arr[] which is sorted and rotated, the task is to find an element in the rotated array (with duplicates) in O(log n) time. Note: Print the index where the key exists. In case of multiple answer print any of them Examples: Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 3 Output: 0 arr[0] = 3 Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 11 Outpu
14 min read
Javascript Program for Search an element in a sorted and rotated array
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.  Example:   Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3
7 min read
Maximum element in a sorted and rotated array
Given a sorted array arr[] of distinct elements which is rotated at some unknown point, the task is to find the maximum element in it.Examples: Input: arr[] = {3, 4, 5, 1, 2} Output: 5Input: arr[] = {1, 2, 3} Output: 3 Approach: A simple solution is to traverse the complete array and find maximum. This solution requires O(n) time. We can do it in O
6 min read
Javascript Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above array is sorted and rotated. Sorted array: {1, 2, 3,
3 min read
Check if an array is sorted and rotated
Given an array arr[] of size n, the task is to return true if it was originally sorted in non-decreasing order and then rotated (including zero rotations). Otherwise, return false. The array may contain duplicates. Examples: Input: arr[] = { 3, 4, 5, 1, 2 }Output: YESExplanation: The above array is sorted and rotatedSorted array: {1, 2, 3, 4, 5}Rot
7 min read
Minimum in a Sorted and Rotated Array
Given a sorted array arr[] (may be distinct or may contain duplicates) of size N that is rotated at some unknown point, the task is to find the minimum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 1Explanation: 1 is the minimum element present in the array. Input: arr[] = {1, 2, 3, 4}Output: 1 Input: arr[] = {2, 1}Output: 1 Usi
8 min read
Count of Pairs with given sum in Rotated Sorted Array
Given an array arr[] of distinct elements size N that is sorted and then around an unknown point, the task is to count the number of pairs in the array having a given sum X. Examples: Input: arr[] = {11, 15, 26, 38, 9, 10}, X = 35Output: 1Explanation: There is a pair (26, 9) with sum 35 Input: arr[] = {11, 15, 6, 7, 9, 10}, X = 16Output: 2 Approach
13 min read
Count elements less than or equal to a given value in a sorted rotated array
Given a sorted array of n distinct integers rotated at some point. Given a value x. The problem is to count all the elements in the array which are less than or equal to x. Examples: Input : arr[] = {4, 5, 8, 1, 3}, x = 6 Output : 4 Input : arr[] = {6, 10, 12, 15, 2, 4, 5}, x = 14 Output : 6 Naive Approach: One by one traverse all the elements of t
15 min read
Sort a Rotated Sorted Array
You are given a rotated sorted array and your aim is to restore its original sort in place.Expected to use O(1) extra space and O(n) time complexity. Examples: Input : [3, 4, 1, 2] Output : [1, 2, 3, 4] Input : [2, 3, 4, 1] Output : [1, 2, 3, 4] We find the point of rotation. Then we rotate array using reversal algorithm. 1. First, find the split p
11 min read
Find if there is a pair with a given sum in the rotated sorted Array
Given an array arr[] of distinct elements size N that is sorted and then rotated around an unknown point, the task is to check if the array has a pair with a given sum X. Examples : Input: arr[] = {11, 15, 6, 8, 9, 10}, X = 16Output: trueExplanation: There is a pair (6, 10) with sum 16 Input: arr[] = {11, 15, 26, 38, 9, 10}, X = 35Output: trueExpla
14 min read
Find the Rotation Count in Rotated Sorted array
Given an array arr[] of size N having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Output: 2Explanation: Initial array must
15+ min read
Count rotations in sorted and rotated linked list
Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k. The idea is to traverse singly linked list to check condition whether current node value is greater than value of next node. If the given condition is true, then break the loop. Otherwise increase the counter variable and increase the node by node
8 min read
Javascript Program For Counting Rotations In Sorted And Rotated Linked List
Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k. The idea is to traverse singly linked list to check condition whether current node value is greater than value of next node. If the given condition is true, then break the loop. Otherwise increase the counter variable and increase the node by node
3 min read
Count number of common elements between a sorted array and a reverse sorted array
Given two arrays consisting of N distinct integers such that the array A[] and B[] are sorted in ascending and descending order respectively, the task is to find the number of values common in both arrays. Examples: Input: A[] = {1, 10, 100}, B[] = {200, 20, 2}Output: 0 Input: A[] = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999}, B[] = {109, 99, 68
15+ min read
Search, Insert, and Delete in an Sorted Array | Array Operations
How to Search in a Sorted Array? In a sorted array, the search operation can be performed by using binary search. Below is the implementation of the above approach: C/C++ Code // C++ program to implement binary search in sorted array #include &lt;bits/stdc++.h&gt; using namespace std; int binarySearch(int arr[], int low, int high, int key) { if (hi
15+ min read
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array. Examples: Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}Output: Yes Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]} Since the resultan
15+ min read
Javascript Program to Print array after it is right rotated K times
Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?Examples :   Input: Array[] = {1, 3, 5, 7, 9}, K = 2. Output: 7 9 1 3 5 Explanation: After 1st rotation - {9, 1, 3, 5, 7} After 2nd rotation - {7, 9, 1, 3, 5} Input: Array[] = {1, 2, 3, 4, 5}, K = 4. Output: 2 3 4 5
2 min read
Print Array after it is right rotated K times where K can be large or negative
Given an array arr[] of size N and a value K (-10^5&lt;K&lt;10^5), the task is to print the array rotated by K times to the right. Examples: Input: arr = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5Explanation: Rotating array 1 time right: 9, 1, 3, 5, 7Rotating array 2 time right: 7, 9, 1, 3, 5 Input: arr = {1, 2, 3, 4, 5}, K = -2Output: 3 4 5 1 2Explan
7 min read
Find the winner in game of rotated Array
Given a circular connected binary array X[] of length N. Considered two players A and B are playing the game on the following move: Choose a sub-array and left-rotate it once. The move is said to be valid if and only if the number of adjacent indices in X[] having different values (after rotation) is strictly greater than the number of adjacent ind
8 min read
Print array after it is right rotated K times
Given an Array of size N and a value K, around which we need to right rotate the array. How do you quickly print the right rotated array?Examples : Input: Array[] = {1, 3, 5, 7, 9}, K = 2.Output: 7 9 1 3 5Explanation:After 1st rotation - {9, 1, 3, 5, 7}After 2nd rotation - {7, 9, 1, 3, 5} Input: Array[] = {1, 2, 3, 4, 5}, K = 4.Output: 2 3 4 5 1 Re
15+ min read
Print array after it is right rotated K times | Set 2
Given an array arr[] of size N and a value K, the task is to print the array rotated by K times to the right. Examples: Input: arr = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5 Input: arr = {1, 2, 3, 4, 5}, K = 4Output: 2 3 4 5 1 Algorithm: The given problem can be solved by reversing subarrays. Below steps can be followed to solve the problem: Reverse
13 min read
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm
Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. A linear time complexity is discussed in the previous post. This problem can also be a very good example for divide and conquer algorithms. Following is divide and conquer algorithm.1) Find the middle elemen
15+ min read
Sort a nearly sorted (or K sorted) array | Set 2 (Gap method - Shell sort)
Given an array, arr[] of N elements, where each element is at most K away from its target position, the task is to devise an algorithm that sorts in O(N*log(K)) time. Examples: Input: arr[] = {10, 9, 8, 7, 4, 70, 60, 50}, K = 4Output: 4 7 8 9 10 50 60 70Explanation:Follow the steps below to sort the array: Start with Gap = K(i.e. 4)10 9 8 7 4 70 60
8 min read
Maximize partitions that if sorted individually makes the whole Array sorted
Given an array arr[]. The task is to divide arr[] into the maximum number of partitions, such that, those partitions if sorted individually make the whole array sorted. Examples: Input: arr[] = { 28, 9, 18, 32, 60, 50, 75, 70 }Output: 4Explanation: Following are the partitions in which the array is divided. If we divide arr[] into four partitions {
5 min read
Sort a nearly sorted (or K sorted) array
Given an array of N elements, where each element is at most K away from its target position, devise an algorithm that sorts in O(N log K) time. Examples: Input: arr[] = {6, 5, 3, 2, 8, 10, 9}, K = 3 Output: arr[] = {2, 3, 5, 6, 8, 9, 10} Input: arr[] = {10, 9, 8, 7, 4, 70, 60, 50}, k = 4Output: arr[] = {4, 7, 8, 9, 10, 50, 60, 70} Recommended Pract
15+ min read
Search equal, bigger or smaller in a sorted array in Java
Given array of sorted integer, search key and search preferences find array position. A search preferences can be: 1) EQUAL - search only for equal key or -1 if not found. It's a regular binary search. 2) EQUAL_OR_SMALLER - search only for equal key or the closest smaller. -1 if not found. 3) EQUAL_OR_BIGGER - search only for equal key or the close
4 min read
Create a Sorted Array Using Binary Search
Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: Input : arr[] = {2, 5, 4, 9, 8} Output : 2 4 5 8 9 Input : arr[] = {10, 45, 98, 35, 45} Output : 10 35 45 45 98 The above problem can be solved efficiently using Binary Search. We create a new array and insert the first element
9 min read
Search an element in a sorted array formed by reversing subarrays from a random index
Given a sorted array arr[] of size N and an integer key, the task is to find the index at which key is present in the array. The given array has been obtained by reversing subarrays {arr[0], arr[R]} and {arr[R + 1], arr[N - 1]} at some random index R. If the key is not present in the array, print -1. Examples: Input: arr[] = {4, 3, 2, 1, 8, 7, 6, 5
8 min read
Search insert position of K in a sorted array
Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it's present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted. Examples: Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is
9 min read