VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sudo-placement1-3-final-destination/

⇱ Sudo Placement[1.3] | Final Destination - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sudo Placement[1.3] | Final Destination

Last Updated : 11 Jul, 2025

Given an array of integers and a number K with initial and final values. Your task is to find the minimum number of steps required to get final value starting from the initial value using the array elements. You can only do add (add operation % 1000) on values to get the final value. At every step, you are allowed to add any of the array elements with modulus operation.

Examples:  

Input: initial = 1, final = 6, a[] = {1, 2, 3, 4} 
Output:
Step 1: (1 + 1 ) % 1000 = 2. 
Step 2: (2 + 4) % 1000 = 6 (which is required final value).

Input: start = 998 end = 2 a[] = {2, 1, 3} 
Output:
Step 1 : (998 + 2) % 1000 = 0. 
Step 2 : (0 + 2) % 1000 = 2. 
OR 
Step 1 : (998 + 1) % 1000 = 999. 
Step 2 : (999 + 3) % 1000 = 2

Approach: 

Since in the above problem the modulus given is 1000, therefore the maximum number of states will be 103. All the states can be checked using simple BFS. Initialize an ans[] array with -1 which marks that the state has not been visited. ans[i] stores the number of steps taken to reach i from start. Initially push the start to the queue, then apply BFS. 

Pop the top element and check if it is equal to the end if it is then print the ans[end]. If the element is not equal to the topmost element, then add the top element with every element in the array and perform a mod operation with 1000. If the added element state has not been visited previously, then push it into the queue. Initialize ans[pushed_element] by ans[top_element] + 1. 

Once all the states are visited, and the state cannot be reached by performing every possible multiplication, then print -1. 

Below is the implementation of the above approach:  


Output
2

Time Complexity: O(N)

Comment