We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Sequence Equation
Sequence Equation
+ 40 comments Simple solution with explanation
From my HackerRank solutions.
Our input provides us n values of x and p(x)
p(x) is a one-to-one function, so it has an inverse. We create the function representing the inverse of p(x), and represent it as an array: int [] p_inverse
We need to find a y where p(p(y)) = x. This equation can be rewritten as
y = p_inverse(p_inverse(x)), which is the version of the equation we use to calculate and print y.import java.util.Scanner; public class Solution { public static void main(String [] args) { /* Create function: p_inverse */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int [] p_inverse = new int[n + 1]; for (int x = 1; x <= n; x++) { int px = scan.nextInt(); p_inverse[px] = x; } scan.close(); /* Calculate and print each y */ for (int x = 1; x <= n; x++) { int y = p_inverse[p_inverse[x]]; System.out.println(y); } } }
Let me know if you have any questions.
+ 16 comments #include <iostream> using namespace std; int main() { int n; cin>>n; int p[n+1]; for(int i=1;i<=n;i++){ int k; cin>>k; p[k]=i; } for(int i=1;i<=n;i++)cout<<p[p[i]]<<endl; return 0; }
+ 11 comments n = int(input().strip()) p = list(map(int,input().strip().split(' '))) for i in range(n): print(p.index(p.index(i+1)+1)+1) ''' Our task is :: For each x from 1 to n , print an integer denoting any valid y satisfying the equation p(p(y)) = x on a new line. Here p(y) means, the value at y index in list p. But the range of y goes from 1 to n, and range of python list goes from 0 to n-1. so make it balanced, we need to add 1 in each time in y to make it equal to python index. for example 3 2 3 1 Now, x goes from 1 to 3 (inclusive), but since the range goes from 0 to n-1, 1 needed to add here to balance it. when i = 0, x = i+1, you need to find that at which index 1 is coming in list p first_index = p.index(i+1) now, u need to find at which index the first_index is coming, but since , the index coming as output in above line is from 0 to n-1, 1 needed to add to balace it second_index = p.index(first_index+1) since this will also be 0 to n-1,, add 1 ans = second_index + 1 I have written a new code so u can understand how each line works ''' n = int(input().strip()) p = list(map(int,input().strip().split(' '))) for i in range(n): x = i+1 first_index = p.index(x) second_index = p.index(first_index + 1) ans = second_index + 1 print(ans)
+ 2 comments Can anybody explain what the problem is in layman's terms? I normally don't have this much trouble deciphering the instructions.
+ 1 comment what is the triple equals sign?
Load more conversations
Sort 1183 Discussions, By:
Please Login in order to post a comment