|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * 1409. Queries on a Permutation With Key |
| 8 | + * |
| 9 | + * Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: |
| 10 | + * In the beginning, you have the permutation P=[1,2,3,...,m]. |
| 11 | + * For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. |
| 12 | + * Notice that the position of queries[i] in P is the result for queries[i]. |
| 13 | + * Return an array containing the result for the given queries. |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * Input: queries = [3,1,2,1], m = 5 |
| 17 | + * Output: [2,1,2,1] |
| 18 | + * Explanation: The queries are processed as follow: |
| 19 | + * For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. |
| 20 | + * For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. |
| 21 | + * For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. |
| 22 | + * For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. |
| 23 | + * Therefore, the array containing the result is [2,1,2,1]. |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * Input: queries = [4,1,2,2], m = 4 |
| 27 | + * Output: [3,1,2,0] |
| 28 | + * |
| 29 | + * Example 3: |
| 30 | + * Input: queries = [7,5,5,8,3], m = 8 |
| 31 | + * Output: [6,5,0,7,5] |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * 1 <= m <= 10^3 |
| 35 | + * 1 <= queries.length <= m |
| 36 | + * 1 <= queries[i] <= m |
| 37 | + * */ |
| 38 | +public class _1409 { |
| 39 | + public static class Solution1 { |
| 40 | + public int[] processQueries(int[] queries, int m) { |
| 41 | + Map<Integer, Integer> indexToValMap = new HashMap<>(); |
| 42 | + for (int i = 1; i <= m; i++) { |
| 43 | + indexToValMap.put(i - 1, i); |
| 44 | + } |
| 45 | + int[] result = new int[queries.length]; |
| 46 | + for (int i = 0; i < queries.length; i++) { |
| 47 | + int val = queries[i]; |
| 48 | + int pos = findPos(indexToValMap, val); |
| 49 | + result[i] = pos; |
| 50 | + for (int j = pos; j > 0; j--) { |
| 51 | + indexToValMap.put(j, indexToValMap.get(j - 1)); |
| 52 | + } |
| 53 | + indexToValMap.put(0, val); |
| 54 | + } |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | + private int findPos(Map<Integer, Integer> map, int val) { |
| 59 | + for (int pos : map.keySet()) { |
| 60 | + if (map.get(pos) == val) { |
| 61 | + return pos; |
| 62 | + } |
| 63 | + } |
| 64 | + return -1; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments