Find a point that lies inside exactly K given squares
Given an integer K and an array arr each of whose element x represents a square with two of its vertices as (0, 0) and (x, x). The task is to find a point which lies in exactly K squares.
Examples:
Input: arr[] = {1, 2, 3, 4}, K = 2
Output: (3, 3)
The point (3, 3) lies inside 3rd and 4th square only.
Input: arr[] = {8, 1, 55, 90}, K = 3
Output: (8, 8)
Approach: Since all squares have a common corner point (0, 0), any point which lies in any square would also lie in any larger square. Hence, we can simply print the other corner of the Kth largest square.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int PointInKSquares( int n, int a[], int k)
{
sort(a, a + n);
return a[n - k];
}
int main()
{
int k = 2;
int a[] = { 1, 2, 3, 4 };
int n = sizeof (a) / sizeof (a[0]);
int x = PointInKSquares(n, a, k);
cout << "(" << x << ", " << x << ")" ;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int PointInKSquares( int n, int a[], int k)
{
Arrays.sort(a);
return a[n - k];
}
public static void main (String[] args) {
int k = 2 ;
int []a = { 1 , 2 , 3 , 4 };
int n = a.length;
int x = PointInKSquares(n, a, k);
System.out.println( "(" + x + ", " + x + ")" );
}
}
|
Python3
def PointInKSquares(n, a, k) :
a.sort()
return a[n - k]
if __name__ = = "__main__" :
k = 2
a = [ 1 , 2 , 3 , 4 ]
n = len (a)
x = PointInKSquares(n, a, k)
print ( "(" , x, "," , x, ")" )
|
C#
using System;
class GFG
{
static int PointInKSquares( int n,
int []a, int k)
{
Array.Sort(a);
return a[n - k];
}
public static void Main (String[] args)
{
int k = 2;
int []a = { 1, 2, 3, 4 };
int n = a.Length;
int x = PointInKSquares(n, a, k);
Console.WriteLine( "(" + x + ", " + x + ")" );
}
}
|
PHP
<?php
function PointInKSquares( $n , $a , $k )
{
sort( $a );
return $a [ $n - $k ];
}
$k = 2;
$a = array (1, 2, 3, 4);
$n = sizeof( $a );
$x = PointInKSquares( $n , $a , $k );
echo "(" . $x . ", " . $x . ")" ;
?>
|
Javascript
<script>
function PointInKSquares(n, a, k)
{
a.sort();
return a[n - k];
}
let k = 2;
let a = [ 1, 2, 3, 4 ];
let n = a.length;
let x = PointInKSquares(n, a, k);
document.write( "(" + x + ", " + x + ")" );
</script>
|
Complexity Analysis:
- Time Complexity: O(nlog(n)), since to sort the elements of the array, the best algorithm takes (n * log n) time.
- Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
09 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...