Easy One Liner Solution along with Intuition.
Let\'s understand the intuition behind the solution with an example:\nGiven - \n\nn = 4\nk = 5\n\n\nNow let us look at all the solution from k=1 to k =12\n\n\n+
**Let\'s understand the intuition behind the solution with an example:**\nGiven - \n```\nn = 4\nk = 5\n```\n\nNow let us look at all the solution from k=1 to k =12\n\n```\n+-----+-------+\n|  k  | Answer|\n+-----+-------+\n|  1  |   1   |\n|  2  |   2   |\n|  3  |   3   |\n|  4  |   2   |\n|  5  |   1   |\n|  6  |   0   |\n---------------\n|  7  |   1   |\n|  8  |   2   |\n|  9  |   3   |\n|  10 |   2   |\n|  11 |   1   |\n|  12 |   0   |\n+-----+-------+\n```\n***As you can see after every  2(n-1) values of \uD835\uDC58, the answers repeat in a pattern. So if we get the answer correct from k = 1 to 2(n-1) then we can deduce the solution for all values of \uD835\uDC58.***\n\n**Explaning the steps by which I arrived to the solution**\n\n1) The below solution works but only when `k <= n`\n\n```\nclass Solution {\n    public int numberOfChild(int n, int k) {\n        return k;\n    }\n}\n```\n\n\n2. The below works only when `k <= 2n - 1.`\nThis formula adjusts the answer based on the distance from \uD835\uDC5B-1.\n```\nclass Solution {\n    public int numberOfChild(int n, int k) {\n         return n-1 - Math.abs(n - 1 - k);\n    }\n}\n```\n\n3. Now mod k with 2 * (n-1) as the pattern repeats. \n```\nclass Solution {\n    public int numberOfChild(int n, int k) {\n        return n-1 - Math.abs(n - 1 - k % (2*(n-1)));\n    }\n}\n```\nThis approach ensures that the solution is efficient and works for all values of \uD835\uDC58.\n\n\n
['Math']