VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-to-find-the-future-closest-date/

⇱ Queries to find the future closest date - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries to find the future closest date

Last Updated : 15 Jul, 2025

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:

  1. Sort the array of dates arr[] by comparing the year first, then the month followed by the day.
  2. After sorting the array in the above step, for each query, find the closest date using binary search to compare two dates use the comparator function.
  3. If no valid date is found, then print "-1".
  4. Otherwise, print the closest date found.

Below is the implementation of the above approach: 


Output: 
23/5/56645
-1
4/12/233

 

Time Complexity: O((N*log N) + (Q*log N)) 
Auxiliary Space: O(1)

Comment