Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the original array from given array obtained after P prefix reversals
Next article icon

Restore the original array from another array generated by given operations

Last Updated : 05 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array b. The array b is obtained initially by array a, by doing the following operations.

  • Choose a fixed point x from array a.
  • Cyclically rotate the array a to the left exactly x times.

Fixed point x is that point where (a[i] = i ). These operations are performed on the array a k times, determine if you will be able to restore the array a given array b.

Examples:

Input : n = 5 , k = 3 , b = { 4,3, 3, 2, 3 }
Output: Yes
Explanation: The array 'a' was initially given as [3, 2, 3, 4, 3]. In the first operation, a specific position, denoted as x=2, was selected. After performing 2 left shifts at this position, the array transformed into [3, 4, 3, 3, 2]. For the second operation, a different fixed point x=3 was chosen, and executing 3 left shifts resulted in the array [3, 2, 3, 4, 3]. Subsequently, in the third operation, the same fixed point x=3 was selected, and after 3 left shifts, the array transformed into [4, 3, 3, 2, 3]. Notably, this final array is equivalent to the array 'b'.

Input : n = 5 , k = 5 , b = { 6, 1, 1, 1, 1 }
Output : No
Explanation : the size of the array is 5 and we are given with 6 as our array element, and our condition specifically says a[i] = i , hence 6 can never satisfy our condition for the cyclic rotation of array.

Approach:

The Idea here is that the last element will always be the one which was our fixed point one step before and now is at the last because we cyclically rotated the array towards left which results in the fixed point array element being at the last of the array. If we try to right rotate the array k times then we will surely be getting our original array a, but if we found and element at the end whose value is greater then the size of the array , then we stop and report that we cannot generate our array a, else we continue right shifting k times. Since right shifting can be a time consuming task we just shift the last index pointer in our array, and % remainder modulus it so that it does not goes out of bounds from the indexes.

Follow the steps to solve the above problem:

  • Begin by setting a boolean flag to true and initializing the variable lastindex to the index of the last element in the array 'b'.
  • Iterate for a maximum of min(n, k) times.
    • Inside the loop, check if the element at the current lastindex is greater than n. If true, set the flag to false and break out of the loop.
    • Otherwise, calculate the distance needed to move lastindex to a new position based on the current element and update lastindex accordingly, moving the calculated distance steps clockwise in the array.
  • Finally, based on the value of the flag, output "Yes" if the array 'a' can be restored or "No" otherwise.

Below is the implementation of above approach:

C++14
#include <bits/stdc++.h> #include <math.h>  using namespace std;  void solve(int n, int k, vector<int> arr) {     bool flag = true;      // Initialize 'lastindex' to the index of the last     // element in the array     int lastindex = n - 1;      // Iterate for a maximum of min(n, k) times to prevent     // exceeding array bounds     for (int i = 0; i < min(n, k); i++) {         // Check if the element at the current 'lastindex'         // is greater than n         if (arr[lastindex] > n) {             // If true, set 'flag' to false and break out of             // the loop             flag = false;             break;         }          // Calculate the distance needed to move 'lastindex'         // to a new position based on the current element         int dist = n - arr[lastindex];          // Update 'lastindex' accordingly, moving dist steps         // clockwise in the array         lastindex = (lastindex + dist) % n;     }      // Output the result based on the value of 'flag'     if (flag)         cout << "Yes" << endl;     else         cout << "No" << endl; }  // Driver Code  int main() {      int n = 5, k = 3;      vector<int> arr = { 4, 3, 3, 2, 3 };      solve(n, k, arr); } 
Java
public class SolveProblem {      static void solve(int n, int k, int[] arr) {         // Initialize 'flag' to true         boolean flag = true;          // Initialize 'lastIndex' to the index of the last         // element in the array         int lastIndex = n - 1;          // Iterate for a maximum of min(n, k) times to prevent         // exceeding array bounds         for (int i = 0; i < Math.min(n, k); i++) {             // Check if the element at the current 'lastIndex'             // is greater than n             if (arr[lastIndex] > n) {                 // If true, set 'flag' to false and break out of                 // the loop                 flag = false;                 break;             }              // Calculate the distance needed to move 'lastIndex'             // to a new position based on the current element             int dist = n - arr[lastIndex];              // Update 'lastIndex' accordingly, moving dist steps             // clockwise in the array             lastIndex = (lastIndex + dist) % n;         }          // Output the result based on the value of 'flag'         if (flag) {             System.out.println("Yes");         } else {             System.out.println("No");         }     }      // Driver Code     public static void main(String[] args) {         int n = 5;         int k = 3;         int[] arr = {4, 3, 3, 2, 3};          solve(n, k, arr);     } } 
Python3
def solve(n, k, arr):     # Initialize 'flag' to True     flag = True          # Initialize 'lastindex' to the index of the last      # element in the array      lastindex = n - 1      # Iterate for a maximum of min(n, k) times to prevent      # exceeding array bounds      for i in range(min(n, k)):         # Check if the element at the current 'lastindex'          # is greater than n          if arr[lastindex] > n:             # If true, set 'flag' to False and break out of              # the loop             flag = False             break          # Calculate the distance needed to move 'lastindex'          # to a new position based on the current element          dist = n - arr[lastindex]                  # Update 'lastindex' accordingly, moving dist steps          # clockwise in the array          lastindex = (lastindex + dist) % n          # Output the result based on the value of 'flag'     if flag:         print("Yes")     else:         print("No")  # Driver Code  n = 5 k = 3 arr = [4, 3, 3, 2, 3]  solve(n, k, arr) 
C#
using System; using System.Collections.Generic;  class Program {     static void Solve(int n, int k, List<int> arr)     {         bool flag = true;          // Initialize 'lastindex' to the index of the last         // element in the array         int lastindex = n - 1;          // Iterate for a maximum of Math.Min(n, k) times to prevent         // exceeding array bounds         for (int i = 0; i < Math.Min(n, k); i++)         {             // Check if the element at the current 'lastindex'             // is greater than n             if (arr[lastindex] > n)             {                 // If true, set 'flag' to false and break out of                 // the loop                 flag = false;                 break;             }              // Calculate the distance needed to move 'lastindex'             // to a new position based on the current element             int dist = n - arr[lastindex];              // Update 'lastindex' accordingly, moving dist steps             // clockwise in the array             lastindex = (lastindex + dist) % n;         }          // Output the result based on the value of 'flag'         if (flag)             Console.WriteLine("Yes");         else             Console.WriteLine("No");     }      // Driver Code     static void Main()     {         int n = 5, k = 3;          List<int> arr = new List<int> { 4, 3, 3, 2, 3 };          Solve(n, k, arr);     } } 
JavaScript
function solve(n, k, arr) {     let flag = true;          // Initialize 'lastindex' to the index of the last      // element in the array      let lastindex = n - 1;      // Iterate for a maximum of min(n, k) times to prevent      // exceeding array bounds      for (let i = 0; i < Math.min(n, k); i++) {              // Check if the element at the current 'lastindex'          // is greater than n          if (arr[lastindex] > n) {                      // If true, set 'flag' to false and break out of              // the loop             flag = false;             break;         }          // Calculate the distance needed to move 'lastindex'          // to a new position based on the current element          let dist = n - arr[lastindex];                  // Update 'lastindex' accordingly, moving dist steps          // clockwise in the array          lastindex = (lastindex + dist) % n;     }          // Output the result based on the value of 'flag'     if (flag)         console.log("Yes");     else         console.log("No"); }  // Driver Code  let n = 5, k = 3; let arr = [4, 3, 3, 2, 3];  solve(n, k, arr); 

Output
Yes 

Time Complexity : O(n), where n is the length of the array.

Auxiliary space : O(1).


Next Article
Find the original array from given array obtained after P prefix reversals
author
sundaransinha
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • Arrays
  • Algorithms-Greedy Algorithms
  • QA - Placement Quizzes-Data Interpretation
  • python-dict
  • Scala-Arrays
  • Volkswagen IT Services
  • Geeks Premier League 2023
Practice Tags :
  • Arrays
  • Arrays
  • python-dict

Similar Reads

  • Find the original array from given array obtained after P prefix reversals
    Given an array arr[] of size N and an integer P (P < N), the task is to find the original array from the array obtained by P prefix reversals where in ith reversal the prefix of size i of the array containing indices in range [0, i-1] was reversed. Examples: Input: arr[] = {4, 2, 1, 3, 5, 6}, P =
    10 min read
  • Find the Initial Array from given array after range sum queries
    Given an array arr[] which is the resultant array when a number of queries are performed on the original array. The queries are of the form [l, r, x] where l is the starting index in the array, r is the ending index in the array and x is the integer elements that have to be added to all the elements
    13 min read
  • Calculate sum of the array generated by given operations
    Given an array arr[] consisting of N strings, the task is to find the total sum of the array brr[] (initially empty) constructed by performing following operations while traversing the given array arr[]: If the array arr[] contains an integer, then insert that integer into the array brr[].If the arr
    8 min read
  • Reduce all array elements to zero by performing given operations thrice
    Given an array arr[] of size N, the task is to convert every array element to 0 by applying the following operations exactly three times: Select a subarray.Increment every element of the subarray by the integer multiple of its length. Finally, print the first and last indices of the subarray involve
    9 min read
  • Find the final sequence of the array after performing given operations
    Given an array arr[] of size N, the task is to perform the following operation exactly N times, Create an empty list of integers b[] and in the ith operation, Append arr[i] to the end of b[].Reverse the elements in b[]. Finally, print the contents of the list b[] after the end of all operations.Exam
    12 min read
  • Restore a permutation from the given helper array
    Given an array Q[] of size N - 1 such that each Q[i] = P[i + 1] - P[i] where P[] is the permutation of the first N natural numbers, the task is to find this permutation. If no valid permutation P[] can be found then print -1. Examples: Input: Q[] = {-2, 1} Output: 3 1 2 Input: Q[] = {1, 1, 1, 1} Out
    7 min read
  • Find original array from given array which is obtained after P prefix reversals | Set-2
    Given an array arr[] of size N and an integer P, the task is to find the original array from the array obtained by P prefix reversals where in ith reversal the prefix of size i of the array containing indices in range [0, i-1] was reversed. Note: P is less than or equal to N Examples: Input: arr[] =
    7 min read
  • Array obtained by repeatedly reversing array after every insertion from given array
    Given an array arr[], the task is to print the array obtained by inserting elements of arr[] one by one into an initially empty array, say arr1[], and reversing the array arr1[] after every insertion. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4 2 1 3Explanation:Operations performed on the array a
    6 min read
  • Find original array from encrypted array (An array of sums of other elements)
    Find original array from a given encrypted array of size n. Encrypted array is obtained by replacing each element of the original array by the sum of the remaining array elements. Examples : Input : arr[] = {10, 14, 12, 13, 11} Output : {5, 1, 3, 2, 4} Original array {5, 1, 3, 2, 4} Encrypted array
    6 min read
  • Modify array to another given array by replacing array elements with the sum of the array | Set-2
    Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences