![]() |
VOOZH | about |
Given an array arr[] consisting of N strings and an array Query[] consisting of Q queries. Each string in arrays arr[] and Query[] is of the form D/M/Y where D, M and Y denotes the date, month and year. For each query, the task is to print the next closest date from the given array arr[]. If no such date exists, print "-1".
Examples:
Input: arr[]={"22/4/1233", "1/3/633", "23/5/56645", "4/12/233"}, Q = 2,
Query[] = {"23/3/4345", "12/3/2"}
Output:
23/5/56645
4/12/233
Explanation:
Query 1: The closest date after "23/3/4345" is "23/5/56645".
Query 2: The closest date after "12/3/2" is "4/12/233".Input: arr[]={"22/4/1233", "4/12/233", "1/3/633", "23/5/56645"}, Q = 1,
Query[] = {"4/4/34234234"}
Output: -1
Naive Approach: The simplest approach for each query in the array Query[] is to traverse the array arr[] and for each date, check if it is greater than the current date or not and if it closest to it or not. After complete traversal of the array, print the closest date obtained. If no date is found, print -1.
Time Complexity: O(N*Q)
Auxiliary Space: O(1)
Efficient Approach: The idea is to sort the given array arr[] using a comparator function. Then use a Binary Search to find the future date closest to each date in Query[]. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
23/5/56645 -1 4/12/233
Time Complexity: O((N*log N) + (Q*log N))
Auxiliary Space: O(1)