Problems - Set 2

Easy

Circular Problem

Determine the position where the A-th item will be delivered in a circle of size B, starting from position C.

public static int findPosition(int A, int B, int C) {
        // Calculate the position
        int position = (C + A - 1) % B;

        // If position is 0, it means we are at the last position in the circle
        return position == 0 ? B : position;
    }

Number Divisibility

Given a number represent in the form of an integer array A, where each element is a digit. We have to find whether there exists any permutation of the array A such that the number becomes divisible by 60. Return 1 if it exists, 0 otherwise.

Approach

  1. Check for 0 (Divisibility by 5 and 2)

    1. The number must contain at least one 0 because the last digit must be 0 for divisibility by 60.

  2. Check for Divisibility by 3:

    1. Compute the sum of the digits in A.

    2. If the sum is divisible by 3, this condition is satisfied.

  3. Check for an Additional Even Digit:

    1. Besides the 0 required for divisibility by 5, ensure there is at least one more even digit (2,4,6,8) to satisfy divisibility by 2.

  4. Check for edge case like all number 0

Line Segment Intersection

Given two straight line segments (represented as a start point and an end point), compute the point of intersection, if any.

Basics

Each segment can be seen as part of an infinite line in 2D space.

We can represent each line in the general form:

Ax+By=C

For a line from (x1,y1) to (x2,y2), the general form is:

  • A=y2−y1

  • B=x1−x2

  • C=A⋅x1+B⋅y1,

For the two lines:

Line 1 (through P1,P2​):

A1=y2−y1, B1=x1−x2, C1=A1x1+B1y1

Line 2 (through P3,P4​):

A2=y4−y,,B2=x3−x4,C2=A2x3+B2y3

Solve the Linear System

Now solve:

A1x+B1y=C1 A2x+B2y=C2

Use Cramer's Rule or matrix inversion. The determinant is:

det=A1B2−A2B1

If det = 0, the lines are parallel or coincident (no unique intersection).

Otherwise, the intersection point (x,y) is:

x=B2C1−B1C2/det

y=A1C2−A2C1/det

Check if the Point Lies on Both Segments

The above point lies on the infinite lines. You must ensure it lies within the bounds of both segments.

For a point r=(x,y) to lie on segment P=(x1,y1) to Q=(x2,y2), it must satisfy:

min⁡(x1,x2) ≤ x ≤ max⁡(x1,x2)

min⁡(y1,y2) ≤ y ≤ max⁡(y1,y2)

Repeat for both segments.

Solution

Tic Tac Toe

Design an algorithm to figure out if someone has won a game of tic-tac-toe.

  • Board is a 3x3 grid.

  • Each cell is either: 'X', 'O', or null / '' (empty).

  • Determine if 'X' or 'O' has won.

  • A win occurs when a player has 3 of their marks in:

    • A row

    • A column

    • A diagonal

Trailing zeros in n factorial

Write an algorithm which computes the number of trailing zeros in n factorial.

Trailing zeros are the zeros at the end of a number.

Example: 120 has 1 trailing zero 1000 has 3 trailing zeros

Trailing zeros are formed when the number is divisible by powers of 10.

What causes a 10 in factorial?

Every time we multiply numbers, a 10 is produced when we multiply 2 × 5.

In a factorial like n! = 1 × 2 × 3 × ... × n, there are many 2s and many 5s.

But 5s are less frequent than 2s, so:

  • The number of 10s = the number of times 5 appears in the prime factors of n!.

So the number of trailing zeros is equal to the number of times 5 appears as a factor in n!.

How do we count how many 5s are there?

We look for:

  • Numbers divisible by 5: these give one 5

  • Numbers divisible by 25: these give two 5s

  • Numbers divisible by 125: these give three 5s, and so on.

So we add:

We stop when the division result becomes zero.

Example: n = 100

So, total number of trailing zeros = 20 + 4 = 24

Smallest Difference

Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference.

Example

Input: a = {1, 3, 15, 11, 2}, b = {23, 127,235, 19, 8}

Output: 3. That is, the pair (11, 8).

Solution 1: Brute-force approach

Time Complexity: O(n × m)

This works by comparing every pair from array a and b using two nested loops.

Solution 2: Optimized Approach (Using Sorting + Two Pointers)

  • Sort both arrays:

  • Use two pointers i and j to walk through a and b:

    • If a[i] < b[j], try next value in a (increase i)

    • If a[i] > b[j], try next value in b (increase j)

    • Always track the current absolute difference

  • Stop when we reach the end of either array.

Time Complexity

  • Sorting: O(n log n + m log m)

  • Linear scan: O(n + m)

  • Total: O(n log n + m log m)

Medium

Operations

Write methods to implement the multiply, subtract, and divide operations for integers. The results of all of these are integers. Use only the add operator

Subtract using only +

To subtract b from a, add the negative of b to a.

Multiply using only +

Multiply a and b by adding a repeatedly |b| times.

Divide using only +

Use repeated subtraction to see how many times b fits into a.

Board Lengths

There are two types of planks, one of length shorter and one of length longer. We must use exactly K planks of wood. Write a method to generate all possible lengths for the board.

Solution 1: Brute Force (Two nested loops)

Loop through all combinations of shorter and longer planks that add up to k.

Time Complexity

  • O(k) because we loop from 0 to k and compute a single value each time.

Solution 2: Optimized Approach (No Set, No Duplicates)

We avoid using a Set and simply generate values in a loop if shorter != longer.

Time Complexity

  • O(k)

  • No duplicate check needed as each value is guaranteed unique if shorter != longer.

Sub Sort

Given an array, find the smallest subarray (from index m to n) such that if this part is sorted, the entire array becomes sorted. We aim to minimize n - m.

  1. Find where the array stops being sorted from left to right.

  2. Find where the array stops being sorted from right to left.

  3. Then:

    • Find min and max in the unsorted region.

    • Expand the left (m) to include any number greater than min.

    • Expand the right (n) to include any number less than max.

Explanation

Given: [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]

  1. Find the first dip from the left where array is no longer sorted: Index 511 > 7

  2. Find the first rise from the right where array is no longer sorted: Index 86 < 7

So the unsorted window is initially from 6 to 8: [7, 12, 6] → But we now find the min = 6, max = 12

  1. Expand m to include any number greater than min (6) → Expand left: 4th index is 10 > 6 → 3rd index is 7 > 6 → 2nd index is 4 < 6 → stop

    So m = 3

  2. Expand n to include any number less than max (12) → 9th is 7 < 12 → 10th is 16 > 12 → stop

    So n = 9

Difficult

Powerful Divisors

Given an integer array A of length N. For every integer X in the array, we have to find out the number of integers Y, such that 1 <= Y <= X, and the number of divisors of Y is a power of 2.

For example, 6 has the following divisors - [1, 2, 3, 6]. This is equal to 4, which is a power of 2. On the other hand, 9 has the following divisors [1, 3, 9] which is 3, which is not a power of 2. Return an array containing the answer for every X in the given array.

Example Input 1: A = [1, 4]

Output 1: [1, 3]

Input 2: A = [5, 10]

Output 2: [4, 8]

Optimized Approach

We can optimize the code by:

  1. Precomputing the divisor counts for all numbers up to the maximum value in the input list.

  2. Using a single array to store the count of "powerful divisors" for each number.

  3. Reusing computed results instead of recalculating them.

Last updated