짬뽕얼큰하게의 맨땅에 헤딩 :: Find the Student that Will Replace the Chalk

Leetcode Problem:

Summary

  • Find the index of the student who will replace the chalk pieces

Approach

  • The solution uses the modulo operator to find the remaining chalk pieces after each student's turn
  • It then iterates through the chalk array to find the student who will run out of chalk first.

Complexity

  • O(n) where n is the number of students

Explain

  • The solution works by first calculating the total amount of chalk available
  • It then uses the modulo operator to find the remaining chalk pieces after each student's turn
  • The student who will run out of chalk first is the one whose index is returned
  • This approach ensures that the student who will replace the chalk is found efficiently, even for large inputs.

Solution Code:


class Solution {
public:
    int chalkReplacer(vector& chalk, int k) {
        long long sum = 0;
        for(int i = 0 ; i < chalk.size(); i++){
            sum += chalk[i];
        }
        k = k % sum;
        for(int i = 0 ; i < chalk.size(); i++){
            k -= chalk[i];
            if (k < 0) return i;
        }
        return 0;
    }
};

'알고리즘' 카테고리의 다른 글

Walking Robot Simulation  (0) 2025.02.11
Sum of Digits of String After Convert  (0) 2025.02.11
Convert 1D Array Into 2D Array  (0) 2025.02.11
Path with Maximum Probability  (0) 2025.02.11
Most Stones Removed with Same Row or Column  (0) 2025.02.11
블로그 이미지

짬뽕얼큰하게

,