Find the Kth position element of the given sequence
Last Updated :
07 Mar, 2022
Given two integers N and K, the task is to find the element at the Kth position if all odd numbers from 1 to N are written down in increasing order followed by all the even numbers from 1 to N in increasing order.
Examples:
Input: N = 10, K = 3
Output: 5
The required sequence is 1, 3, 5, 7, 9, 2, 4, 6, 8 and 10.
Input: N = 7, K = 7
Output: 6
Approach: It is known that the Nth even number is given by 2 * K and the Nth odd number is given by 2 * K – 1. But since the even numbers are written after (N + 1) / 2 odd numbers here. Therefore, Kth even number is given by 2 * (K – (N + 1) / 2) and the odd numbers will remain the same as 2 * K – 1
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int kthNum( int n, int k)
{
int a = (n + 1) / 2;
if (k > a)
return (2 * (k - a));
return (2 * k - 1);
}
int main()
{
int n = 7, k = 7;
cout << kthNum(n, k);
return 0;
}
|
Java
class GFG
{
static int kthNum( int n, int k)
{
int a = (n + 1 ) / 2 ;
if (k > a)
return ( 2 * (k - a));
return ( 2 * k - 1 );
}
public static void main(String []args)
{
int n = 7 , k = 7 ;
System.out.println(kthNum(n, k));
}
}
|
Python3
def kthNum(n, k) :
a = (n + 1 ) / / 2 ;
if (k > a) :
return ( 2 * (k - a));
return ( 2 * k - 1 );
if __name__ = = "__main__" :
n = 7 ; k = 7 ;
print (kthNum(n, k));
|
C#
using System;
class GFG
{
static int kthNum( int n, int k)
{
int a = (n + 1) / 2;
if (k > a)
return (2 * (k - a));
return (2 * k - 1);
}
public static void Main(String []args)
{
int n = 7, k = 7;
Console.WriteLine(kthNum(n, k));
}
}
|
Javascript
<script>
function kthNum(n, k)
{
var a = (n + 1) / 2;
if (k > a)
return (2 * (k - a));
return (2 * k - 1);
}
var n = 7, k = 7;
document.write(kthNum(n, k));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...