Sansa and XOR

Sort by

recency

|

48 Discussions

|

  • + 0 comments

    Isnt a great exercise, it requires you to know the attributes of XOR: Namely: Associatitive A^(B^C) = (A^B)^C Commutative A^B = B^A Self inverse: A^A = 0

    The first and second example written down, gives you some clue: The 4 elements and up being even number of A's (if you call first number A) and also all other nunebrs. Therefore it will be always 0. The first example written down A,B,C ends up A^B. But not because they are on the edge, but rather the indexes being even.

  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn sansa_and_xor(arr: &[i32]) -> i32 {
        //Time complexity: O(n)
        //Space complexity (ignoring input): O(1)
        //A number will appear in {(index+1)*(n-index)} subsequences
        //In case arr.len() is par, the appearences of any number will be par as well
        if arr.len() % 2 == 0 {
            return 0;
        }
        let mut xor_value = 0;
        for index in 0..arr.len() {
            let appearences = (index + 1) * (arr.len() - index);
            if appearences % 2 != 0 {
                xor_value ^= arr[index]
            }
        }
        return xor_value;
    }
    
  • + 0 comments

    Python best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    def sansa_and_xor(arr):
        #Time complexity: O(n)
        #Space complexity (ignoring input): O(1)
        #A number will appear in {(index+1)*(n-index)} subsequences
        #In case arr.len() is par, the appearences of any number will be par as well
        xor_value = 0
        for index in range(0, len(arr)):
            frequency_number = (index + 1) * (len(arr) - index)
            if frequency_number % 2 != 0:
                xor_value ^= arr[index]
    
        return xor_value
    
  • + 0 comments

    Python 3

    from functools import reduce
    from operator import xor
    
    
    def sansaXor(arr: list[int]) -> int:
        return reduce(xor, arr[::2]) if len(arr) % 2 else 0
    
  • + 0 comments

    Pythonic 1 liner:

    return reduce(lambda res, i: res ^ arr[i], range(0, len(arr), 2), 0) if len(arr) % 2 else 0