Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task, but to write efficient code and improve your logic, you need to go beyond this.

To perform operations like data encryption or data compression, you need to deal with a deeper level of storage structures. Since Bitwise operators work on the ground level in our system they are faster, they optimize the program to a good level.

Midnight hospitals are faster than normal operators as they deal directly with bit-level data and hence can be used to optimize the time complexity of different programs. Before going to the tricks, let's first brush up on some important concepts of Bitwise operations.

Following are the six widely used Bitwise operators:

  1. Not ~
  2. AND &
  3. OR |
  4. LEFT SHIFT <<
  5. RIGHT SHIFT >>
  6. XOR ^

Bitwise NOT

This is a unary operator used when you need to flip all the bits for a number. In other words, this operator returns the one's complement of a binary number.

For example,

X=2 =(010)2

~x=(101)2 =5

Bitwise AND

This is a binary operator, and as the name depicts, it just returns the output of the AND operation on each and every single bit of the two operands.

If both the bits that are being compared are 1, then only the result is one else; it is zero.

For example,

X=2 =(010)2

Y=5 =(101)2

X AND Y=(000)2 =0

Bitwise OR

This Binary operator just returns the output of or operation performed on each of the bits from on the two inputs.

For example,

X=2 =(010)2

Y=5 =(101)2

X OR Y=(111)2 =7

Bitwise XOR

This Bitwise operator takes two inputs of the same length and compares each of their bits. If both of the bits that are being compared are the same, then the result would be zero; else, it would return 1

For example,

X=2 =(010)2

Y=5 =(101)2

X XOR Y=(111)2 =7

Bitwise LEFT-SHIFT

This binary operator, technically speaking, shifts the n bits from the m number to the left and appends 0 at the end. Basically, it returns the value of m * 2^n, and if the two operands are m and n

For example,

X=1 =(01)2

Y=2 =(10)2

X << Y=(0100)2 =4

Or you can understand this as:

X= 1

Y= 2

X<< Y = 1*22 =4

Bitwise RIGHT-SHIFT

This binary operator, technically speaking this operator shifts the n bits from the m number to the right and appends 1 at the end. It basically returns the value of m / 2^n, where m and n are the two operands.

For example,

X=4 =(0100)2

Y=1

X << Y=(010)2 =2

Or you can understand this as:

X= 4

Y= 1

X>> Y = 4/21 =2

Tricks of Bit-Wise Operators

Now let’s move towards up of the important techniques or tricks that you can use in your programs welding with BITS in your straight should help you to write time-efficient quotes for the operations that you almost use in every algorithm in order to build a good program.

1. Swapping two numbers using Bitwise operators

 Algorithm to swap two numbers without using any kind of extra space as well as pointers:

  • Read inputs x and y.
  • Set x = x ^ y (X XOR Y).
  • Set y = y ^ x
  • Assign x ^ y to x again.
  • Print the swapped results

This is an efficient way to swap two variables in your program.

2. Calculate the XOR of all the numbers from 1 to n

By observing the XOR of all the numbers from 0 to n you would find a common pattern sequence in them.

Using the logic behind this pattern, an efficient algorithm can be designed in such a way that you would be able to find the XOR of all the numbers from 0 to n in constant time complexity.

The algorithm is:

  • Read N.
  • Calculate N%4.
  • Set I =N%4.
  • Check the value of I:

a) For I==0

Print N.

b) For I==1

Print N.

c) For I==2

Print N+1.

d) For I==3

Print 0.

This efficient way prints the XOR of 1 to n numbers in O(1) time complexity, whereas a normal algorithm with a naive approach would take O(N) time for the same.

Using bit operators, find a number's MSB (Most Significant Bit) efficiently

The most efficient way to find the most significant bit of a fixed-size interior would be to use an algorithm that should directly deal with the bits.

The algorithm to find the MSB would be:

  1. Read N.
  2. Set n= n | n >>1
  3. Set n= n | n >>2
  4. Set n= n | n >>4
  5. Set n= n | n >>8
  6. Set n= n | n >>16
  7. Set n = (( n+1)>>1 | (n & (1 <<((sizeof(n)*CHAR_BIT-1)));
  8. Return N.

This algorithm can find the most significant bit of a number in just O(1) time complexity.

Check if a number is a power of two.

You can directly use this trick to find whether a number is a power of two or not.

  1. Read n.
  2. Initialize result= n && (!(n&(n-1)))
  3. Return result.

Directly return TRUE OR FALSE in constant time and can help you to save a lot of time in many programs.

Convert a given binary number to an integer

The auto keyword in c is used for this task and returns the desired value

For example,

int main(){
auto value= 0b0110010
printf("%d", value);
}

Flipping all bits of a number

When you need to flip all the bits of a number, you can easily do the same by subtracting it from any number in which all the bits are set.

For example,

Number= 0011010

The number in which all the bits are set = 111111

Subtraction= 1100101 (numbers with flipped bits)

Algorithm:

  1. Read Number.
  2. Initialize n= number.
  3. Set n= n | n >>1
  4. Set n= n | n >>2
  5. Set n= n | n >>4
  6. Set n= n | n >>8
  7. Set n= n | n >>16
  8. Return (n - number).

Like this, you could get the number with all the flipped bits in constant time.

Check if the sequence of bits of any number has an alternate pattern.

Whenever you need to find any pattern in a sequence of bits, you can use the Bitwise XOR operation to check whether there is an alternate pattern.

The below algorithm can be used for the same.

  1. Read N
  2. Check the value of :((n+1)&n)
    • if it is equal to 0
      return 1.
    • else
      return 0.

This algorithm is a helpful trick you can use whenever you need to find any number with a specific type of bits sequence.

Finding the number of leading and trailing zeros in any number

You can directly use the inbuilt GCC function to find the number of leading and trailing zeros of any number.

For example:

  1. Read N
  2. Set leading_zero = ___builtin_clz(n).
  3. return leading_zero.

These are some useful Bitwise manipulation tricks you can use in your various programs to reduce their time complexity and hence write efficient codes.