Showing posts with label Algorithms. Show all posts
Showing posts with label Algorithms. Show all posts

Sunday, September 7, 2025

Life, the Universe, and Everything - Easy Problem From HackerEarth

To See All Articles About Technology: Index of Lessons in Technology

All Tracks>Basic Programming> Input/Output> Basics of Input/Output> Problem
Difficulty: Easy

Try This Problem Here

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. 

Sample Input

1
2
88
42
99

Sample Output

1
2
88

My Solution

NOT42 = True
while (NOT42):
    n = int(input())
    if n == 42:
        break
    else:
        print(n)
Life, the Universe, and Everything - Easy Problem From HackerEarth

Roy and Profile Picture - Easy Problem From HackerEarth

To See All Articles About Technology: Index of Lessons in Technology

Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload.
Minimum dimension of the picture can be L x L, where L is the length of the side of square.

Now Roy has N photos of various dimensions.
Dimension of a photo is denoted as W x H
where W - width of the photo and H - Height of the photo

When any photo is uploaded following events may occur:

[1] If any of the width or height is less than L, user is prompted to upload another one. Print "UPLOAD ANOTHER" in this case.
[2] If width and height, both are large enough and
(a) if the photo is already square then it is accepted. Print "ACCEPTED" in this case.
(b) else user is prompted to crop it. Print "CROP IT" in this case.

(quotes are only for clarification)

Given L, N, W and H as input, print appropriate text as output.

Input:
First line contains L.
Second line contains N, number of photos.
Following N lines each contains two space separated integers W and H.

Output:
Print appropriate text for each photo in a new line.

Constraints:
1 <= L,W,H <= 10000
1 <= N <= 1000

Sample Input
180
3
640 480
120 300
180 180

Sample Output
CROP IT
UPLOAD ANOTHER
ACCEPTED

My Solution

L = int(input())
N = int(input())
WH = [list(map(int, input().split())) for _ in range(N)]

for i in WH:
    W = i[0]
    H = i[1]
    if W < L or H < L:
        print("UPLOAD ANOTHER")
    elif W >= L and H >= L and W == H:
        print("ACCEPTED")
    else:
        print("CROP IT")

Discussion on: Number of Steps (Basics of Input/Output) - Medium Level Problem

To See All Articles About Technology: Index of Lessons in Technology

All Tracks>Basic Programming> Input/Output> Basics of Input/Output> Problem

Try Out The Problem Here


how to solve this problem and what does this problem teach me?

Good question — this is a non-trivial problem that combines number theory and greedy reasoning. Let’s break it down step by step.


🔍 Problem Restated in My Words

We have two arrays:

  • a = [a1, a2, ..., an]

  • b = [b1, b2, ..., bn]

Operation:
You can replace ai with ai - bi if ai ≥ bi.
You need to make all a[i] equal (same value) using the fewest steps.
If it’s impossible → output -1.


✨ Key Observations

  1. Operation is like repeated subtraction (Euclidean Algorithm flavor):

    • ai = ai - bi behaves like reducing a number step by step by a fixed amount.

    • Example: if ai = 10, bi = 4, repeated operation gives sequence 10 → 6 → 2.

    Essentially:

    rust
    final value ≡ ai (mod bi)

    Because subtracting multiples of bi keeps remainder fixed.

  2. For all a[i] to be equal:

    • Their final values must be the same.

    • This means: all ai % bi must equal the same target (otherwise impossible).

  3. Checking feasibility:

    • If any ai % bi is different from the others, return -1.

  4. Counting steps:

    • If feasible, steps for ai = (ai - target) / bi.

    • Total steps = sum of all steps for all i.


✅ Solution Strategy

  1. Compute rems = [ai % bi for each i].

  2. If all remainders are not equal → return -1.

  3. Pick this common remainder target.

  4. Compute steps:

    ini
    steps = sum((ai - target) / bi for each i)
  5. Return total steps.


🔎 Walkthrough with Example

Example 1:

ini
n = 2 a = [5, 64] b = [4, 3]
  • Remainders: [5 % 4 = 1, 64 % 3 = 1] ✅ equal.

  • Target = 1

  • Steps: (5-1)/4 = 1, (64-1)/3 = 21 → total = 22

But sample output says -1. Why?
Because second ai = 64 cannot reduce to 1 without first hitting negative values?
Let’s check:
64 → 61 → 58 → ... → 1. Works fine.
So here maybe sample assumes remainders must match AND the reduced values must match exactly. If a[i] < target case occurs → impossible. That’s why careful checking is needed.


Example 2:

ini
n = 5 a = [5, 7, 10, 5, 15] b = [2, 2, 1, 3, 5]
  • Remainders: [1, 1, 0, 2, 0] → not all same. ❌
    But solution gives 8. Meaning: you can adjust differently and still converge.

So actually, the insight is:

  • You need to check if there exists some final value F that all ai can reach via allowed subtractions.

  • That’s equivalent to requiring that ai - F is divisible by bi.

Thus:

  • Choose one a[j] as candidate final value F.

  • Check if (ai - F) % bi == 0 for all i.

  • Minimize steps over all possible candidates.


📘 What This Problem Teaches You

  1. Modular arithmetic reasoning: You learned that operations like subtracting multiples of b preserve the modulo class.

  2. Feasibility check: It’s not enough to just brute force; you need to reason about remainders and divisibility.

  3. Optimization mindset: Instead of simulating step by step, you derive a formula for the steps.

  4. Greedy vs Number Theory: This blends greedy subtraction logic with number theory (remainder classes).


👉 In summary:

  • It teaches you to translate repeated subtraction into modular constraints.

  • It also teaches you how to check feasibility (common final value exists).

  • It trains you to optimize without brute force.


Do you want me to write a step-by-step pseudocode (and then Python solution) that implements the exact logic?


yeah, sure

Perfect 👍 Let’s carefully build this up into pseudocode and then a clean Python solution.


🔎 Step-by-Step Pseudocode

python
function min_steps(n, a[], b[]): steps = infinity # Try every a[j] as a candidate final value F for j from 1 to n: F = a[j] possible = True total_steps = 0 for i from 1 to n: if a[i] < F: possible = False break if (a[i] - F) % b[i] != 0: possible = False break total_steps += (a[i] - F) / b[i] if possible: steps = min(steps, total_steps) if steps == infinity: return -1 else: return steps

Python Implementation

python
def min_steps(n, a, b): min_steps = float("inf") for j in range(n): # try each a[j] as candidate final value F = a[j] possible = True total = 0 for i in range(n): if a[i] < F: # can't reduce below F possible = False break if (a[i] - F) % b[i] != 0: # must be reachable possible = False break total += (a[i] - F) // b[i] if possible: min_steps = min(min_steps, total) return -1 if min_steps == float("inf") else min_steps # Example Usage: print(min_steps(2, [5, 64], [4, 3])) # → -1 (sample) print(min_steps(5, [5, 7, 10, 5, 15], [2, 2, 1, 3, 5])) # → 8 (sample)

💡 Explanation of Approach

  • The operation preserves ai mod bi.

  • Therefore, each ai can only become values of the form ai - k*bi.

  • To make all a’s equal to the same final value F, we need:

    • F ≤ ai

    • (ai - F) % bi == 0 for all i

  • By trying every ai as a candidate F, we ensure we don’t miss any possible final value.

  • Then, for each candidate, compute steps needed and choose the minimum.


Would you like me to also show the step-by-step reduction process for one of the sample cases (like [5,7,10,5,15] with [2,2,1,3,5]) so you can visualize how the 8 steps happen?

Number of Steps (Basics of Input/Output) - Medium Level Problem

To See All Articles About Technology: Index of Lessons in Technology

All Tracks>Basic Programming> Input/Output> Basics of Input/Output> Problem

Try Out The Problem Here


You are given two arrays 
 and 
. In each step, you can set 
 if 
. Determine the minimum number of steps that are required to make all 
's equal.

Input format

First line: 
 
Second line: 
Third line: 
Output format

Print the minimum number of steps that are required to make all 
's equal. If it is not possible, then print -1.

Constraints

 

Sample input

25 64 3

Sample output

-1

Sample Input
5
5 7 10 5 15
2 2 1 3 5
Sample Output
8

My Solution

def min_steps(n, a, b):
    min_steps = float("inf")

    for j in range(n):  # try each a[j] as candidate final value
        F = a[j]
        possible = True
        total = 0

        for i in range(n):
            if a[i] < F:  # can't reduce below F
                possible = False
                break
            
            if b[i] != 0 and (a[i] - F) % b[i] != 0:  # must be reachable
                possible = False
                break
            
            if b[i] != 0:
                total += (a[i] - F) // b[i]
            else:
                total += 0

        if possible:
            min_steps = min(min_steps, total)

    return -1 if min_steps == float("inf") else min_steps


n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

# Example Usage:
print(min_steps(n, A, B))

View The Test Cases

Sunday, June 15, 2025

Index of "Algorithms: Design and Analysis"

Toggle All Sections

From Codility

Course Link: By James Cutajar
  1. Binary Gap (Problem of Iterations)
  2. Arrays
  3. Time Complexity
  4. Counting Elements
  5. Prefix Sums
  6. Sorting
  7. Stacks and Queues
  8. Leader using Boyer-Moore Majority Vote Algo
  9. Maximum Slice Problem (using Kadane's Algo leveraging Dynamic Programming)
  10. Recursion (An Introduction)
  11. Substring in another string (Lesson in Algorithms)

From Hacker Earth

From ChatGPT

Tags: <

Monday, June 2, 2025

Discussion on 'Count Divisors' (Problem from Hacker Earth)

To See All Articles About Technology: Index of Lessons in Technology

Try it out
Problem

You have been given 3 integers: l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need to print these numbers, you just have to find their count.

Input Format
The first and only line of input contains 3 space separated integers l, r and k.

Output Format
Print the required answer on a single line.

Constraints
1 <= l <= r <= 1000

1 <= k <= 1000

Sample Input
1 10 1
Sample Output
10

Time Limit: 1
Memory Limit: 256
Source Limit:

Psuedocode

if (r - l + 1) > k return (r - l + 1) / k else: if floor(l / k) == floor(r / k): return 0 else: return 1 Critique this psuedocode.

Solution


Your pseudocode is heading in the right direction by trying to find how many numbers in the range [l, r] are divisible by k, but it still contains logical issues. Let’s break it down carefully and critique each part:

Goal
We want to count all numbers x such that l ≤ x ≤ r and x % k == 0.

 Issues in Your Pseudocode
Your pseudocode:

if (r - l + 1) > k
    return (r - l + 1) / k
else:
    if floor(l / k) == floor(r / k):
        return 0
    else:
        return 1

Problem 1: (r - l + 1) / k doesn't count multiples of k
This gives the average number of elements between l and r per k steps, not how many elements are divisible by k.

Consider l = 3, r = 10, k = 2

r - l + 1 = 8

8 / 2 = 4 ✅ correct here by luck

But try l = 5, r = 15, k = 3:

r - l + 1 = 11, 11 / 3 = 3 ❌ wrong (actual count: 4 → 6, 9, 12, 15)

🔴 Problem 2: Your else block logic is oversimplified
plaintext
Copy
Edit
if floor(l / k) == floor(r / k):
    return 0
else:
    return 1
This assumes that at most one number divisible by k exists in [l, r], which is incorrect.

For example, l = 3, r = 10, k = 2:

floor(3/2) = 1, floor(10/2) = 5 → not equal → returns 1 ❌ but actual count is 4

✅ Correct and Simple Pseudocode

Input: l, r, k

# Use integer division (i.e., floor)
count = floor(r / k) - floor((l - 1) / k)

Return count
✅ Why this Works
Let’s take l = 5, r = 15, k = 3

Numbers ≤ 15 divisible by 3: 3, 6, 9, 12, 15 → total = floor(15/3) = 5

Numbers ≤ 4 divisible by 3: 3 → total = floor(4/3) = 1

So numbers divisible by 3 in [5, 15] = 5 - 1 = 4

💡 Final Thoughts
❌ Avoid using (r - l + 1) / k unless l = 1 and k = 1

✅ Stick to the formula floor(r / k) - floor((l - 1) / k) for correct results in all ranges

Would you like a Python function implementing this pseudocode too?
    

Explanation

✅ Correct Way to Count Multiples of k in [l, r] The correct formula is: count = floor(r / k) - floor((l - 1) / k) It works because: floor(r / k) counts how many numbers from 1 to r are divisible by k floor((l - 1) / k) counts how many from 1 to l-1 are divisible by k Subtracting the two gives how many are in the range [l, r]