Given two integers N and M, the task is to find the vertex diagonally opposite to the Mth vertex of an N-sided polygon.
Input: N = 6, M = 2
It can be observed from the image above that the vertex opposite to vertex 5 is 2.
Input: N = 8, M = 5
It can be observed from the image above that the vertex opposite to vertex 8 is 1.
Approach: The following two cases need to be considered to solve the given problem:
- If M > N / 2: The vertex will always be M — (N / 2).
- If M ≤ N / 2: The vertex will always be M + (N / 2).
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.