Jar of Candies

Easy
0/40
Average time to solve is 20m
2 upvotes
Asked in companies
AdobeOla

Problem statement

There is a jar full of candies for sale at a mall counter. Jar has the capacity ‘N’. That is, jar can contain maximum ‘N’ candies when a jar is full. At any point in time jar can not have 0 or fewer candies.

Given the number ‘K’, the number of candies the customer wants. Your task is to return the candies left in the jar.

Note:

If 'K' is greater than 'N', return -1 denoting the invalid order.

For example:

Given if 'N' = 10, 'K' = 5. Then 5 candies are left in the jar after the event.
Detailed explanation ( Input/output format, Notes, Images )

Input format:

The first line of input contains an integer ‘T’ denoting the number of test cases.

The first and the only line of each test case contains two space-separated integers N and K, where ‘N’ is the number of candies in jar and ‘K’ is the number of candies the customer requires.

Output format:

For each test case, return the candies left in the jar. If the order is invalid return -1.

The output of each test case will be printed in a separate line.

Note:

You don’t need to print anything; it has already been taken care of. You just need to implement the given function.

Constraints:

1 <= T <= 5
1 <= N, K <= 10^4

Time Limit: 1 second

Sample Input 1:

2
5 3
5 6

Sample Output 1:

2
-1

Explanation of the Sample Input 1:

For the first test case:
The jar had 5 candies and the customer asked for 3, therefore leftover candies will be (5 - 3) = 2. Hence 2 candies are left in a jar.

For the second test case:
The jar had 5 candies and the customer asked for 6, Hence it is an invalid order, therefore return -1.    

Sample Input 2:

2
4 3
1 1

Sample Output 2:

1
0
Hint

can you think about ‘left = N-K’?

Approaches (1)
Comparing Candies

The main idea is to check if K is greater than N or not.

  • If K is lesser than N, therefore, we can give the customer K candies and return the remaining candies in the jar by subtracting K from N.
  • If K is greater than N therefore, we can't give customer K candies, Hence return -1.
Time Complexity

O(1).

 

This is because comparing 2 numbers is constant time work.

Space Complexity

O(1).

 

Since we are not using any extra space to keep track of the elements.

Code Solution
(100% EXP penalty)
Jar of Candies
Full screen
Console