Open In App

Index Mapping (or Trivial Hashing) with negatives allowed

Last Updated : 02 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Index Mapping (also known as Trivial Hashing) is a simple form of hashing where the data is directly mapped to an index in a hash table. The hash function used in this method is typically the identity function, which maps the input data to itself. In this case, the key of the data is used as the index in the hash table, and the value is stored at that index.

For example, if we have a hash table of size 10 and we want to store the value “apple” with the key “a”, the trivial hashing function would simply map the key “a” to the index “a” in the hash table, and store the value “apple” at that index.

One of the main advantages of Index Mapping is its simplicity. The hash function is easy to understand and implement, and the data can be easily retrieved using the key. However, it also has some limitations. The main disadvantage is that it can only be used for small data sets, as the size of the hash table has to be the same as the number of keys. Additionally, it doesn’t handle collisions, so if two keys map to the same index, one of the data will be overwritten.

Given a limited range array contains both positive and non-positive numbers, i.e., elements are in the range from -MAX to +MAX. Our task is to search if some number is present in the array or not in O(1) time.
Since the range is limited, we can use index mapping (or trivial hashing). We use values as the index in a big array. Therefore we can search and insert elements in O(1) time.
 

hmap

How to handle negative numbers? 
The idea is to use a 2D array of size hash[MAX+1][2]

Algorithm:

Assign all the values of the hash matrix as 0.

Traverse the given array:

  •     If the element ele is non negative assign 
    • hash[ele][0] as 1.
  •     Else take the absolute value of ele and 
    •  assign hash[ele][1] as 1.

To search any element x in the array. 

  • If X is non-negative check if hash[X][0] is 1 or not. If hash[X][0] is one then the number is present else not present.
  • If X is negative take the absolute value of X and then check if hash[X][1] is 1 or not. If hash[X][1] is one then the number is present

Below is the implementation of the above idea. 

C++




// CPP program to implement direct index mapping
// with negative values allowed.
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
 
// Since array is global, it is initialized as 0.
bool has[MAX + 1][2];
 
// searching if X is Present in the given array
// or not.
bool search(int X)
{
    if (X >= 0) {
        if (has[X][0] == 1)
            return true;
        else
            return false;
    }
 
    // if X is negative take the absolute
    // value of X.
    X = abs(X);
    if (has[X][1] == 1)
        return true;
 
    return false;
}
 
void insert(int a[], int n)
{
    for (int i = 0; i < n; i++) {
        if (a[i] >= 0)
            has[a[i]][0] = 1;
       else
            has[abs(a[i])][1] = 1;
    }
}
 
// Driver code
int main()
{
    int a[] = { -1, 9, -5, -8, -5, -2 };
    int n = sizeof(a)/sizeof(a[0]);
    insert(a, n);
    int X = -5;
    if (search(X) == true)
       cout << "Present";
    else
       cout << "Not Present";
    return 0;
}


Java




// Java program to implement direct index
// mapping with negative values allowed.
class GFG
{
 
final static int MAX = 1000;
 
// Since array is global, it
// is initialized as 0.
static boolean[][] has = new boolean[MAX + 1][2];
 
// searching if X is Present in
// the given array or not.
static boolean search(int X)
{
    if (X >= 0)
    {
        if (has[X][0] == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
 
    // if X is negative take the
    // absolute value of X.
    X = Math.abs(X);
    if (has[X][1] == true)
    {
        return true;
    }
 
    return false;
}
 
static void insert(int a[], int n)
{
    for (int i = 0; i < n; i++)
    {
        if (a[i] >= 0)
        {
            has[a[i]][0] = true;
        }
        else
        {
            int abs_i = Math.Abs(a[i]);
            has[abs_i][1] = true;
        }
    }
}
 
// Driver code
public static void main(String args[])
{
    int a[] = {-1, 9, -5, -8, -5, -2};
    int n = a.length;
    insert(a, n);
    int X = -5;
    if (search(X) == true)
    {
        System.out.println("Present");
    }
    else
    {
        System.out.println("Not Present");
    }
}
}
 
// This code is contributed
// by 29AjayKumar


Python3




# Python3 program to implement direct index
# mapping with negative values allowed.
 
# Searching if X is Present in the
# given array or not.
def search(X):
 
    if X >= 0:
        return has[X][0] == 1
 
    # if X is negative take the absolute
    # value of X.
    X = abs(X)
    return has[X][1] == 1
 
def insert(a, n):
 
    for i in range(0, n):
        if a[i] >= 0:
            has[a[i]][0] = 1
        else:
            has[abs(a[i])][1] = 1
 
# Driver code
if __name__ == "__main__":
 
    a = [-1, 9, -5, -8, -5, -2]
    n = len(a)
 
    MAX = 1000
     
    # Since array is global, it is
    # initialized as 0.
    has = [[0 for i in range(2)]
              for j in range(MAX + 1)]
    insert(a, n)
 
    X = -5
    if search(X) == True:
        print("Present")
    else:
        print("Not Present")
 
# This code is contributed by Rituraj Jain


C#





Javascript




<script>
 
// JavaScript program to implement direct index
// mapping with negative values allowed.
 
let MAX = 1000;
 
// Since array is global, it
// is initialized as 0.
let has = new Array(MAX+1);
for(let i=0;i<MAX+1;i++)
{
    has[i]=new Array(2);
    for(let j=0;j<2;j++)
        has[i][j]=0;
}
 
// searching if X is Present in
// the given array or not.
function search(X)
{
    if (X >= 0)
    {
        if (has[X][0] == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
   
    // if X is negative take the
    // absolute value of X.
    X = Math.abs(X);
    if (has[X][1] == true)
    {
        return true;
    }
   
    return false;   
}
 
function insert(a,n)
{
    for (let i = 0; i < n; i++)
    {
        if (a[i] >= 0)
        {
            has[a[i]][0] = true;
        }
        else
        {
            let abs_i = Math.abs(a[i]);
            has[abs_i][1] = true;
        }
    }
}
 
// Driver code
let a=[-1, 9, -5, -8, -5, -2];
let n = a.length;
    insert(a, n);
    let X = -5;
    if (search(X) == true)
    {
        document.write("Present");
    }
    else
    {
        document.write("Not Present");
    }
 
 
// This code is contributed by rag2127
// corrected by akashish__
 
</script>


Output

Present

Time Complexity: The time complexity of the above algorithm is O(N), where N is the size of the given array.
Space Complexity: The space complexity of the above algorithm is O(N), because we are using an array of max size.

 



Previous Article
Next Article

Similar Reads

Sorting using trivial hash function
We have read about various sorting algorithms such as heap sort, bubble sort, merge sort and others. Here we will see how can we sort N elements using a hash array. But this algorithm has a limitation. We can sort only those N elements, where the value of elements is not large (typically not above 10^6). Examples: Input : 9 4 3 5 8 Output : 3 4 5 8
15+ min read
Sum of Fibonacci Numbers with alternate negatives
Given a positive integer n, the task is to find the value of F1 - F2 + F3 -..........+ (-1)n+1Fn where Fi denotes i-th Fibonacci number.Fibonacci Numbers: The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... In mathematical terms, the sequence Fn of Fibonacci numbers is defined
12 min read
Maximize the difference between two subsets of a set with negatives
Given an of integers of size N. The task is to separate these integers into two groups g1 and g2 such that (sum of elements of g1) - (sum of elements of g2) becomes maximum. Your task is to print the value of result. We may keep one subset as empty. Examples: Input : 3, 7, -4, 10, -11, 2 Output : 37 Explanation: g1: 3, 7, 10, 2 g2: -4, -11 result =
4 min read
Remove all negatives from the given Array
Given an array arr[] of size N, the task is to remove all negative elements from this array. Examples: Input: arr[] = {3, -4}Output: {3}Explanation: The only negative element of the array is -4. Input: arr[] = {1, -3, 2}Output: {1, 2} Approach 1: The given problem can be solved using the following steps : Create a vector newArr to store only positi
7 min read
Minimum index i such that all the elements from index i to given index are equal
Given an array arr[] of integers and an integer pos, the task is to find the minimum index i such that all the elements from index i to index pos are equal. Examples: Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 3 Output: 1 Elements in index range [1, 3] are all equal to 1. Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 5 Output: 5 Brute Force Approach: A br
12 min read
Find a Fixed Point (Value equal to index) in a given array | Duplicates Allowed
Given an array of n integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the array can be negative. Examples: Input: arr[] = {-10, -5, 0, 3, 7} Output
13 min read
Minimum cost to reach end of array when a maximum jump of K index is allowed
Given an array arr[] of N integers and an integer K, one can move from an index i to any other j if j &lt;= i + k. The cost of moving from one index i to the other index j is abs(arr[i] - arr[j]). Initially, we start from the index 0 and we need to reach the last index i.e. N - 1. The task is to reach the last index in the minimum cost possible.Exa
12 min read
Efficient method to store a Lower Triangular Matrix using row-major mapping
Given a lower triangular matrix Mat[][], the task is to store the matrix using row-major mapping. Lower Triangular Matrix: A Lower Triangular Matrix is a square matrix in which the lower triangular part of a matrix consists of non-zero elements and the upper triangular part consists of 0s. The Lower Triangular Matrix for a 2D matrix Mat[][] is math
11 min read
Efficient method to store a Lower Triangular Matrix using Column-major mapping
Given a lower triangular matrix Mat[][], the task is to store the matrix using column-major mapping. Lower Triangular Matrix: A Lower Triangular Matrix is a square matrix in which the lower triangular part of a matrix consists of non-zero elements and the upper triangular part consists of 0s. The Lower Triangular Matrix for a 2D matrix Mat[][] is m
10 min read
Check if mapping is possible to make sum of first array larger than second array
Given a positive integer K and two arrays A[] and B[] of size N and M respectively, each containing elements in the range [1, K]. The task is to map all numbers from 1 to K with a function f, such that f(1)&lt;f(2)&lt;f(3)&lt;...&lt;f(K), and find whether the sum of f(A[i]) for 0≤i&lt;N is greater than the sum of f(B[i]) for 0≤i&lt;M. Examples: Inp
6 min read
Article Tags :
Practice Tags :