LeetCode 1421: NPV Queries

Database

Problem Description

Explanation:

Given a list of integers nums, we need to support two types of queries:

  1. Query(Type=1, P): Add P to all elements in the list
  2. Query(Type=2, P): Return the sum of all elements in the list modulo P

To efficiently handle these queries, we can maintain a running sum of all elements in the list. When a query of type 1 is received, we simply add P to the running sum. When a query of type 2 is received, we return the running sum modulo P.

: :

Solutions

class NPVQueries {
    long runningSum = 0;

    public void query(int type, int p) {
        if (type == 1) {
            runningSum += p;
        } else if (type == 2) {
            System.out.println(runningSum % p);
        }
    }
}

Loading editor...