Dynamic Array

Sort by

recency

|

110 Discussions

|

  • + 0 comments

    c++ solution the code does literally what the instructions say

    vector<int> dynamicArray(int n, vector<vector<int>> queries) {
        vector<int> res;
        vector<vector<int>> arr(n);
        int lastAnswer = 0;
        
        for (auto e : queries) {
            int q = e[0], x = e[1], y = e[2];
            
            int idx = (x ^ lastAnswer) % n;
            if (q==1) {
                arr[idx].push_back(y);
            } else {
                lastAnswer = arr[idx][y % arr[idx].size()];
                res.push_back(lastAnswer);
            }
        }
        return res;
    }
    
  • + 0 comments
    def dynamicArray(n, queries):
        answers = [0]
        arr = [[] for i in range(n)]
    
        for q in queries:
            idx = (q[1] ^ answers[-1]) % n
            if q[0] == 1:
                arr[idx].append(q[2])
            else:
                answers.append(arr[idx][q[2] % len(arr[idx])])
    
        return answers[1:]
    
  • + 0 comments

    Javascript

    function dynamicArray(n: number, queries: number[][]): number[] {
      const arr = new Array(n);
      let lastAnswer = 0;
      const answers: number[] = [];
      
      queries.forEach(([qType, x, y]) => {
        const idx = (x ^ lastAnswer) % n;
        if (!arr[idx]) {
          arr[idx] = [];
        }
        
        if (qType === 1) {
          arr[idx].push(y);
        } else if (qType === 2) {
          lastAnswer = arr[idx][y % arrSize(arr[idx])];
          answers.push(lastAnswer);
        }
      });
      
      return answers;
    }
    
  • + 0 comments

    Python 3

    def dynamicArray(n, queries):
        arr = [[]for _ in range(n)]
        lastAnswer = 0
        result = []
        for querie in queries:
            x = querie[1]
            y = querie[2]
            
            idx = ((x ^ lastAnswer)% n)
    				
            if (querie[0]==1):
                arr[idx].append(y)
            
            if (querie[0]==2):
                lastAnswer = arr[idx][y % len(arr[idx])]
                result.append(lastAnswer)
        return result
     
    
  • + 0 comments

    Awful phrasing of question, once again. Even though this is one of the more straightforward questions, it was baffling to go through query 2 and think back as to what the person asking the question wanted.

    The answers array came out of nowhere; especially when all the prompts in the question talk about printing the query.

    It is a fairly straightforward question. Hint, make an answers array; during query 2, instead of printing just store it in the array. Return the array at the end.