Queries to find the XOR of an Array after replacing all occurrences of X by Y

Given an array arr[] consisting of N distinct integers and queries Q[][] of the type {X, Y}, the task for each query is to find the bitwise XOR of all the array elements after replacing X by** Y** in the array.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 5} Q = {(1, 4) (3, 6) (2, 3)}_

Output:4 1 0

Explanation:

Query 1: The array modifies to {4, 2, 3, 4, 5} and XOR = 4

Query 2: The array modifies to {4, 2, 6, 4, 5} and XOR = 1

Query 3: The array modifies to {4, 3, 6, 4, 5} and XOR = 0

Input:_ arr[] = {5, 7, 8, 9, } Q = {(5, 6) (8, 1)}_

Output:_ 0 9_

Explanation:

Query 1: The array modifies to {6, 7, 8, 9} and XOR = 0

Query 2: The array modifies to {6, 7, 1, 9} and XOR = 9

Approach:

The approach is to use the Bitwise XOR property:

  • Suppose, there are three elements A, Band and X, and their Xor is, total_xor = A ^ B ^ X.
  • To remove the contribution of X from total_xor, perform** total_xor ^ X**. It can be verified from the fact that **A ^ B ^ X ^ X = A ^ B **(XOR of an element with itself is 0).
  • To add the contribution of Y in the total_xor, simply perform total_xor ^ Y.

Below is the implementation of the above approach:

  • C++14

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Stores the bitwise XOR

// of array elements

**int** total_xor;

// Function to find the total xor

**void** initialize_xor(``**int** arr[], **int** n)

{

// Loop to find the xor

// of all the elements

**for** (``**int** i = 0; i < n; i++) {

total_xor = total_xor ^ arr[i];

}

}

// Function to find the XOR

// after replacing all occurrences

// of X by Y for Q queries

**void** find_xor(``**int** X, **int** Y)

{

// Remove contribution of

// X from total_xor

total_xor = total_xor ^ X;

// Adding contribution of

// Y to total_xor

total_xor = total_xor ^ Y;

// Print total_xor

cout << total_xor << "\n"``;

}

// Driver Code

**int** main()

{

**int** arr[] = { 5, 7, 8, 9 };

**int** n = **sizeof**``(arr) / **sizeof**``(arr[0]);

initialize_xor(arr, n);

vector<vector<``**int**``> > Q = { { 5, 6 }, { 8, 1 } };

**for** (``**int** i = 0; i < Q.size(); i++) {

find_xor(Q[i][0], Q[i][1]);

}

**return** 0;

}

Output:

0
9

Time Complexity:_ O(N + sizeof(Q))_

Auxiliary Space:_ O(1)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #bit magic #mathematical #bitwise-xor #css #python

What is GEEK

Buddha Community

Queries to find the XOR of an Array after replacing all occurrences of X by Y

Queries to find the XOR of an Array after replacing all occurrences of X by Y

Given an array arr[] consisting of N distinct integers and queries Q[][] of the type {X, Y}, the task for each query is to find the bitwise XOR of all the array elements after replacing X by** Y** in the array.

Examples:

Input:_ arr[] = {1, 2, 3, 4, 5} Q = {(1, 4) (3, 6) (2, 3)}_

Output:4 1 0

Explanation:

Query 1: The array modifies to {4, 2, 3, 4, 5} and XOR = 4

Query 2: The array modifies to {4, 2, 6, 4, 5} and XOR = 1

Query 3: The array modifies to {4, 3, 6, 4, 5} and XOR = 0

Input:_ arr[] = {5, 7, 8, 9, } Q = {(5, 6) (8, 1)}_

Output:_ 0 9_

Explanation:

Query 1: The array modifies to {6, 7, 8, 9} and XOR = 0

Query 2: The array modifies to {6, 7, 1, 9} and XOR = 9

Approach:

The approach is to use the Bitwise XOR property:

  • Suppose, there are three elements A, Band and X, and their Xor is, total_xor = A ^ B ^ X.
  • To remove the contribution of X from total_xor, perform** total_xor ^ X**. It can be verified from the fact that **A ^ B ^ X ^ X = A ^ B **(XOR of an element with itself is 0).
  • To add the contribution of Y in the total_xor, simply perform total_xor ^ Y.

Below is the implementation of the above approach:

  • C++14

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Stores the bitwise XOR

// of array elements

**int** total_xor;

// Function to find the total xor

**void** initialize_xor(``**int** arr[], **int** n)

{

// Loop to find the xor

// of all the elements

**for** (``**int** i = 0; i < n; i++) {

total_xor = total_xor ^ arr[i];

}

}

// Function to find the XOR

// after replacing all occurrences

// of X by Y for Q queries

**void** find_xor(``**int** X, **int** Y)

{

// Remove contribution of

// X from total_xor

total_xor = total_xor ^ X;

// Adding contribution of

// Y to total_xor

total_xor = total_xor ^ Y;

// Print total_xor

cout << total_xor << "\n"``;

}

// Driver Code

**int** main()

{

**int** arr[] = { 5, 7, 8, 9 };

**int** n = **sizeof**``(arr) / **sizeof**``(arr[0]);

initialize_xor(arr, n);

vector<vector<``**int**``> > Q = { { 5, 6 }, { 8, 1 } };

**for** (``**int** i = 0; i < Q.size(); i++) {

find_xor(Q[i][0], Q[i][1]);

}

**return** 0;

}

Output:

0
9

Time Complexity:_ O(N + sizeof(Q))_

Auxiliary Space:_ O(1)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #bit magic #mathematical #bitwise-xor #css #python

Ahebwe  Oscar

Ahebwe Oscar

1620185280

How model queries work in Django

How model queries work in Django

Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.

**Read More : **How to make Chatbot in Python.

Read More : Django Admin Full Customization step by step

let’s just get into this diagram that I made so in here:

django queries aboutDescribe each parameter in Django querset

we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.

Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.

#django #django model queries #django orm #django queries #django query #model django query #model query #query with django

Justyn  Ortiz

Justyn Ortiz

1598428800

Construct a List using the given Q XOR queries

Given a list S that initially contains a single value 0. Below are the Q queries of the following types:

  • 0 X: Insert X in the list
  • 1 X: For every element A in S, replace it by A XOR X.

The task is to print all the element in the list in increasing order after performing the given Q queries.

Examples:

Input:_ Q[][] = { {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5} }_

Output:_ 1 2 3 7_

Explanation:

[0] (initial value)

[0 6] (add 6 to list)

[0 6 3] (add 3 to list)

[0 6 3 2] (add 2 to list)

[4 2 7 6] (XOR each element by 4)

[1 7 2 3] (XOR each element by 5)

Thus sorted order after performing queries is [1 2 3 7]

Input:_ Q[][]= {{0, 2}, {1, 3}, {0, 5} }_

Output:_ 1 3 5_

Explanation:

[0] (initial value)

[0 2] (add 2 to list)

[3 1] (XOR each element by 3)

[3 1 5] (add 5 to list)

Thus sorted order after performing queries is [1 3 5]

Naive Approach: The simplest approach to solve the problem is:

  1. Initialize a list with 0 then traverse for each query and do the following:
  • For query type 0 add given value in the list.
  • For query type 1 traverse list and update every element with their respective Bitwise XOR with value.
  1. After all the queries performed, print the final list in increasing order.

Time Complexity:_ O(N*Q), where N is the length of the list and Q is the number of queries_

Auxiliary Space:_ O(1)_

Efficient Approach: It is much easier to process the numbers in reverse order by keeping track of the cumulative Bitwise XOR working from right to left. Follow the steps below to solve the problem:

  1. Initialize a variable xor with** 0.**
  2. Iterate over the query array from right to left, add xor^value to the list while query type is 0 otherwise update xor with xor^value.
  3. After traversing query add xor to the list and sort the final list.
  4. Print the final list after the above operations.

Below is the implementation of the above approach:

  • Java
  • Python3
  • C#

// Java program for the above approach

**import** java.util.*;

**class** GFG {

// Function to return required list

// after performing all the queries

**static** List<Integer> ConstructList(``**int**``[][] Q)

{

// Store cumulative Bitwise XOR

**int** xor = 0``;

// Initialize final list to return

List<Integer> ans = **new** ArrayList<>();

// Perform each query

**for** (``**int** i = Q.length - 1``; i >= 0``; i--) {

**if** (Q[i][``0``] == 0``)

ans.add(Q[i][``1``] ^ xor);

**else**

xor ^= Q[i][``1``];

}

// The initial value of 0

ans.add(xor);

// Sort the list

Collections.sort(ans);

// Return final list

**return** ans;

}

// Driver Code

**public** **static** **void** main(String[] args)

{

// Given Queries

**int**``[][] Q = {

{ 0``, 6 }, { 0``, 3 }, { 0``, 2 },

{ 1``, 4 }, { 1``, 5 }

};

// Function Call

System.out.println(ConstructList(Q));

}

}

Output:

[1, 2, 3, 7]

Time Complexity:_ O(Q * log(Q))_, where Q is the number of queries.

Auxiliary Space:_ O(N)_, where N is the number of elements in the resultant list.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #bit magic #array-range-queries #bitwise-xor #google

Find the sum of array after performing every query

Given an array arr[] of size Nand Q queries where every query contains two integers X and Y, the task is to find the sum of array after performing each Q queries such that for every query, the element in the array arr[] with value X is updated to Y. Find the sum of the array after every query.

Examples:

Input:_ arr[] ={1, 2, 3, 4}, Q = {(1, 2), (3, 4), (2, 4)}_

Output:_ 11 12 16_

Explanation:

1st operation is to replace each 1 with 2

So array becomes ar[ ] ={2, 2, 3, 4} ans sum = 11

2nd operation is to replace each 3 with 4

So array becomes ar[ ] ={2, 2, 4, 4} ans sum = 12

3rd operation is to replace each 2 with 4

So array becomes ar[ ] ={4, 4, 4, 4} ans sum = 16

Input:_ arr[] = {1}, Q = {(1, 2)}_

Output:_ 2 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The naive approach is to traverse every query and for each query update each element in the array arr[] with value X to Y by traversing the array. Print the sum of all elements in arr[] after each query is performed.

Time Complexity:_ O(N*Q) _

Auxiliary Space:_ O(1)_

Efficient Approach: To optimize the above approach, the idea is to compute the sum of all the element in the array(say sumarr[] and store the frequency of all element in an unordered_map(Say M). For each query (X, Y) do the following:

  1. Find the frequency of X from unordered_map M.
  2. Decrease sum by X*M[X], for excluding the sum of X.
  3. Increase sum by Y*M[X], for excluding the sum of Y.
  4. Increase frequency of Y in map by M[X].
  5. Finally, print the sum and remove X from the map M.

Below is the implementation of the above approach

  • C++14
  • Python3

// C++ program for the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function that solves the given queries

**void** solve(``**int** ar[], **int** n, **int** b[],

**int** c[], **int** q)

{

// This map will store the

// frequency of each element

unordered_map<``**int**``, **int**``> mp;

// sum stores the sum of

// all elements of array

**int** sum = 0;

**for** (``**int** x = 0; x < n; x++) {

sum += ar[x];

mp[ar[x]]++;

}

// Process the queries

**for** (``**int** x = 0; x < q; x++) {

// Find occurrence of

// b[x] from map

**int** occur1 = mp[b[x]];

// Decrease sum

sum = sum - occur1 * b[x];

// Erase b[x] from map

mp.erase(b[x]);

// Increase sum

sum = sum + occur1 * c[x];

// Increase frequency

// of c[x] in map

mp] += occur1;

// Print sum

cout << sum << " "``;

}

}

// Driver Code

**int** main()

{

// Given arr[]

**int** ar[] = { 1, 2, 3, 4 };

**int** n = 4;

// Given Queries

**int** q = 3;

**int** b[] = { 1, 3, 2 };

**int** c[] = { 2, 4, 4 };

// Function Call

solve(ar, n, b, c, q);

**return** 0;

}

Output:

11 12 16

Time Complexity: O(N + Q)

Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #data structures #array-range-queries #cpp-map #frequency-counting

Alayna  Rippin

Alayna Rippin

1596962520

Queries to find the Lower Bound of K from Prefix Sum Array

Given an array A[ ] consisting of non-negative integers and matrix Q[ ][ ] consisting of queries of the following two types:

  • **(1, l, val): **Update A[l] to A[l] + val.
  • **(2, K): **Find the lower_bound of **K **in the prefix sum array of A[ ]. If the lower_bound does not exist print -1.

The task for each query of second type is to print the index of lower_bound of value K.

Examples:

_Input: __A[ ] = {1, 2, 3, 5, 8}, Q[ ][ ] = {{1, 0, 2}, {2, 5}, {1, 3, 5}} _

_Output: __1 _

Explanation:

Query 1: Update A[0] to A[0] + 2. Now A[ ] = {3, 2, 3, 5, 8}

_Query 2: lower_bound of K = 5 in the prefix sum array {3, 5, 8, 13, 21} is 5 and index = 1. _

Query 3: Update A[3] to A[3] + 5. Now A[ ] = {3, 2, 3, 10, 8}

_Input: __A[ ] = {4, 1, 12, 8, 20}, Q[ ] = {{2, 50}, {1, 3, 12}, {2, 50}} _

_Output: __-1 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive approach:

The simplest approach is to firstly build a prefix sum array of given array A[ ], and for queries of Type 1, update values and recalculate the prefix sum. For query of Type 2, perform a Binary Search on the prefix sum array to find lower bound.

Time Complexity:_ O(Q*(N*logn))_

_Auxiliary Space: _O(N)

Efficient Approach:

The above approach can be optimized using Fenwick Tree. Using this Data Structure, the update queries in prefix sum array can be performed in logarithmic time.

Follow the steps below to solve the problem:

  • Construct the Prefix Sum Array using Fenwick Tree.
  • For queries of Type 1, while** l > 0**, add val to A[l] traverse to the parent node by adding least significant bit in l.
  • For queries of Type 2, perform the Binary Search on the Fenwick Tree to obtain the lower bound.
  • Whenever a prefix sum greater than **K appears, **store that **index **and traverse the left part of the Fenwick Tree. Otherwise, traverse the right part of the Fenwick Tree Now, perform Binary Search.
  • Finally, print the required index.

Below is the implementation of the above approach:

  • Java
  • C#

// Java program to implement

// the above appraoch

**import** java.util.*;

**import** java.io.*;

**class** GFG {

// Function to calculate and return

// the sum of arr[0..index]

**static** **int** getSum(``**int** BITree[],

**int** index)

{

**int** ans = 0``;

index += 1``;

// Traverse ancestors

// of BITree[index]

**while** (index > 0``) {

// Update the sum of current

// element of BIT to ans

ans += BITree[index];

// Update index to that

// of the parent node in

// getSum() view by

// subtracting LSB(Least

// Significant Bit)

index -= index & (-index);

}

**return** ans;

}

// Function to update the Binary Index

// Tree by replacing all ancestores of

// index by their respective sum with val

**static** **void** updateBIT(``**int** BITree[],

**int** n, **int** index, **int** val)

{

index = index + 1``;

// Traverse all ancestors

// and sum with 'val'.

**while** (index <= n) {

// Add 'val' to current

// node of BIT

BITree[index] += val;

// Update index to that

// of the parent node in

// updateBit() view by

// adding LSB(Least

// Significant Bit)

index += index & (-index);

}

}

// Function to construct the Binary

// Indexed Tree for the given array

**static** **int**``[] constructBITree(

**int** arr[], **int** n)

{

// Initialize the

// Binary Indexed Tree

**int**``[] BITree = **new** **int**``[n + 1``];

**for** (``**int** i = 0``; i <= n; i++)

BITree[i] = 0``;

// Store the actual values in

// BITree[] using update()

**for** (``**int** i = 0``; i < n; i++)

updateBIT(BITree, n, i, arr[i]);

**return** BITree;

}

// Function to obtian and return

// the index of lower_bound of k

**static** **int** getLowerBound(``**int** BITree[],

**int**``[] arr, **int** n, **int** k)

{

**int** lb = -``1``;

**int** l = 0``, r = n - 1``;

**while** (l <= r) {

**int** mid = l + (r - l) / 2``;

**if** (getSum(BITree, mid) >= k) {

r = mid - 1``;

lb = mid;

}

**else**

l = mid + 1``;

}

**return** lb;

}

**static** **void** performQueries(``**int** A[], **int** n, **int** q[][])

{

// Store the Binary Indexed Tree

**int**``[] BITree = constructBITree(A, n);

// Solve each query in Q

**for** (``**int** i = 0``; i < q.length; i++) {

**int** id = q[i][``0``];

**if** (id == 1``) {

**int** idx = q[i][``1``];

**int** val = q[i][``2``];

A[idx] += val;

// Update the values of all

// ancestors of idx

updateBIT(BITree, n, idx, val);

}

**else** {

**int** k = q[i][``1``];

**int** lb = getLowerBound(

BITree, A, n, k);

System.out.println(lb);

}

}

}

// Driver Code

**public** **static** **void** main(String[] args)

{

**int** A[] = { 1``, 2``, 3``, 5``, 8 };

**int** n = A.length;

**int**``[][] q = { { 1``, 0``, 2 },

{ 2``, 5 },

{ 1``, 3``, 5 } };

performQueries(A, n, q);

}

}

Output:

1

Time Complexity:_ O(Q*(logN)2)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #bit magic #mathematical #searching #array-range-queries #bit #prefix-sum