JPMorgan Chase & Co. – Cohort - India | Hyderabad - SWE | 2024 | OA
Anonymous User
3429

Question 1:


public static int findNumOfPairs(List<Integer> a, List<Integer> b) {
     PriorityQueue<Integer> pq1 = new PriorityQueue<>(Collections.reverseOrder());
     PriorityQueue<Integer> pq2 = new PriorityQueue<>(Collections.reverseOrder());
     
     for(Integer i: a) pq1.offer(i);
     for(Integer i: b) pq2.offer(i);
     
     int c = 0;
     for(int i = 0; i < a.size(); i++) {
         if(pq1.peek().compareTo(pq2.peek()) == 1) {
             c++;
             pq1.poll();
             pq2.poll();
         } else {
             if(pq2.size() == 0) break;
             pq2.poll();
         }
     }
     return c;
    }

Question 2:


public static String rplForm(char[] w, int s, String substr) {
        for(int i = 0; i < substr.length(); i++) {
            if(w[s + i] == '?') {
                w[s + i] = substr.charAt(i);
            } else if(w[s + i] != substr.charAt(i)) return null;
        }
        for(int i = 0; i < w.length; i++) {
            if(w[i] == '?') {
                w[i] = 'a';
            } 
        }
        return new String(w);
    }
    public static String getSmallestString(String word, String substr) {
        String smlRes = null;
        
        for(int i = 0; i <= word.length() - substr.length(); i++) {
            boolean canPlaceSubstr = true;
            for(int j = 0; j < substr.length(); j++) {
                if(word.charAt(i + j) != '?' && word.charAt(i + j) != substr.charAt(j)) {
                    canPlaceSubstr = false;
                    break;
                }
            }
            
            if(canPlaceSubstr) {
                char[] w = word.toCharArray();
                String r = rplForm(w, i, substr);
                if(r != null) {
                    if(smlRes == null || r.compareTo(smlRes) < 0) smlRes = r;
                }
            }
        }
        return smlRes != null ? smlRes : "-1";
    }
Comments (7)