k-th number in the Odd-Even sequence
Given two numbers n and k, find the k-th number in the Odd-Even sequence made of n. The Odd-Even sequence contains first contains all odd numbers from 1 to n then all even numbers in set 1 to n.
Examples :
Input : n = 5, k = 3
Output : 5
In this example, the Odd-Even is
{1, 3, 5, 2, 4}.
The third number in sequence is 5.
Naive Approach :
The first approach is simply make a Odd-Even sequence and then find k-th element in it.
C++
#include <bits/stdc++.h>
using namespace std;
int findK( int n, int k)
{
vector< long > a;
for ( int i = 1; i < n; i++)
if (i % 2 == 1)
a.push_back(i);
for ( int i = 1; i < n; i++)
if (i % 2 == 0)
a.push_back(i);
return (a[k - 1]);
}
int main()
{
long n = 10, k = 3;
cout << findK(n, k) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int findK( int n, int k)
{
ArrayList<Integer> a = new ArrayList<Integer>(n);
for ( int i = 1 ; i < n; i++)
if (i % 2 == 1 )
a.add(i);
for ( int i = 1 ; i < n; i++)
if (i % 2 == 0 )
a.add(i);
return (a.get(k - 1 ));
}
public static void main(String[] args)
{
int n = 10 , k = 3 ;
System.out.println(findK(n, k));
}
}
|
Python3
def findK (n, k ):
a = list ()
i = 1
while i < n:
a.append(i)
i = i + 2
i = 2
while i < n:
a.append(i)
i = i + 2
return (a[k - 1 ])
n = 10
k = 3
print (findK(n, k))
|
C#
using System;
using System.Collections;
class GFG{
static int findK( int n, int k)
{
ArrayList a = new ArrayList(n);
for ( int i = 1; i < n; i++)
if (i % 2 == 1)
a.Add(i);
for ( int i = 1; i < n; i++)
if (i % 2 == 0)
a.Add(i);
return ( int )(a[k - 1]);
}
static void Main()
{
int n = 10, k = 3;
Console.WriteLine(findK(n, k));
}
}
|
PHP
<?php
function findK( $n , $k )
{
$a ;
$index = 0;
for ( $i = 1; $i < $n ; $i ++)
if ( $i % 2 == 1)
$a [ $index ++] = $i ;
for ( $i = 1; $i < $n ; $i ++)
if ( $i % 2 == 0)
$a [ $index ++] = $i ;
return ( $a [ $k - 1]);
}
$n = 10;
$k = 3;
echo findK( $n , $k );
?>
|
Javascript
<script>
function findK(n, k)
{
let a = [];
for (let i = 1; i < n; i++)
if (i % 2 == 1)
a.push(i);
for (let i = 1; i < n; i++)
if (i % 2 == 0)
a.push(i);
return (a[k - 1]);
}
let n = 10, k = 3;
document.write(findK(n, k));
</script>
|
Output :
5
Time complexity: O(n), for an O(1) approach read the approach discussed here.
Space Complexity: O(n) since using an auxiliary array
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...