Java Interview Practice Problem (Beginner): Input IDs in Batches

  • Post last modified:September 10, 2023
  • Reading time:2 mins read

Problem

  • We have a query that takes a list of large input IDs and executes them against the database.
  • DB team asked the backend development team to batch this query instead of overwhelming the database with multiple input IDs.
  • So, we have been given a list of input IDs that can be large in size, Our job is to batch this list of IDs into smaller size lists ( sublist ).

Example

Input 

  • Input contains list of ids of size 10.
[18375, 82597, 10448, 81028, 23008, 80880, 82329, 85845, 30751, 13613]

batch size = 4

Output

  • The output contains a batched list of size 3.
[18375, 82597, 10448]
[81028, 23008, 80880]
[82329, 85845, 30751]
[13613]

Before jumping to the solution consider giving an attempt.

Solution

Sample Input Data

  • We are generating a list of size 1,000 IDs. and for sample input, we are picking random IDs between 1 to 100,000.
List<Integer> ids = IntStream.rangeClosed(1, 1000)
      .mapToObj(i -> new Random().nextInt(100_000))
      .toList();

Solution

  • We will use the sublist method provided by Java collection which takes the start and end index of the list to return values in that bucket.
  • In order to create N batch sizes we need to iterate over a list of input IDs and compute the start and end index for each iteration.
  • the start is initially 0 and moves with a window of batch size. end is wherever the start is plus the batch size.
  • for the last window, we may or may not have batch size IDs, hence we are using min to compute whichever is smaller Choose that one.
    public static List<List<Integer>> solution(List<Integer> ids, int batch_size){
        int start = 0;
        List<List<Integer>> batchedList = new ArrayList<>();
        while (start < ids.size()){
            batchedList.add(
                ids.subList(start, Math.min(ids.size(), start + batch_size))
            );
            start+=batch_size;
        }
        return batchedList;
    }

Code

Find all the code for this & other exercises on GitHub

Over to youWrite down your solution in the comment section for others to get back to it

Before You Leave

Other Problems List

Leave a Reply