Sort by

recency

|

529 Discussions

|

  • + 0 comments

    This a is bit more intuitive approach.

    def condition(i: int, k: int, n: int, a: set) -> bool:
        return 0 < i + k <= n and (i + k) not in a
    
    
    def absolutePermutation(n: int, k: int) -> int | list[int]:
        ans = [-1 for _ in range(n + 1)]
        a = set()
        for i in range(1, n + 1):
            if condition(i, -k, n, a) is True:
                ans[i] = i - k
                a.add(i - k)
            elif condition(i, k, n, a) is True:
                ans[i] = i + k
                a.add(i + k)
            else:
                return [-1]
        return ans[1:]
    
  • + 0 comments

    can't understand question

  • + 0 comments

    Java solution:

    public static List<Integer> absolutePermutation(int n, int k) {
      // Write your code here
    
      List<Integer> result = new ArrayList<>();
    
      if (k == 0) {
        for (int i = 1; i <= n; i++) {
          result.add(i);
        }
        return result;
      }
      if (n % (2 * k) != 0 || k > n || n == 0) {
        return Collections.singletonList(-1);
      }
    
      boolean add = true; // add or substract
      for (int i = 1; i <= n; i++) {
        if (add) {
          result.add(i + k);
    
        } else {
          result.add(i - k);
        }
    
        if (i % k == 0) {
          add = !add;
        }
      }
    
      return result;
    }
    }
    
  • + 1 comment

    Python

    def absolutePermutation(n, k):

    if k !=0 and n% (2*k) !=0:
        return [-1]
    if k == 0:
        return list(range(1, n+1))
    return [(u + k if (u-1) % (2*k) + 1 <= k else u - k) for u in range(1, n+1)]
    
  • + 0 comments

    swift

    func absolutePermutation(n: Int, k: Int) -> [Int] {
        var results: [Int] = [Int]()
        var isUpper: Bool = false
        
        if k == 0 { return Array(1 ... n) }
        
        for number in 0 ... n - 1 {        
            if number % k == 0 { isUpper = !isUpper }
            
            if isUpper { results.append((number + 1) + k) }
            else { results.append((number + 1) - k) }
        
            if results.last! > n { return [-1] }
        }
        return results
    }