Question

Problem 1 You are given an array A of integers and an integer k. Implement an algorithm that determines, in linear time, the

Coded in Java. Also advised to use class java.util.HashMap

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Problem 1:

Algorithm:

findKthrepeated(int[] arr, int k)

Step 1: Create an empty HashMap

Step 2: Store the elements of array into the HashMap as keys and their frequencies as values

Step 3: Traverse through the map and find the key which the at least k value

Code:

import java.util.HashMap;

public class Algorithm {
    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 2, 2, 5, 6, 3, 2, 7};
        System.out.println(findKthrepeated(arr, 3));

    }

    //Function to find the element which exists k times
    public static int findKthrepeated(int[] arr, int k) {
        int ans = -1;
        //Create a new HashMap which can store Integer type keys and values
        HashMap<Integer, Integer> map = new HashMap<>();

        //Store the elements of array with their respective frequency in the HashMap
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
        }

        //Traverse the map and find the element(key) which has the frequency greater than equal to K
        for (int key : map.keySet()) {
            if (map.get(key) >= k) {
                ans = key;
                return ans;
            }
        }
        return ans;
    }
}

import java.util.HashMap: public class Algorithm { public static void main(String[] args) { int[] arr = · {1, 2, 3, 4, 2, 2,

Output: We get the output 2 as its frequency is greater than k, which is 3.

2 Process finished with exit code o

Problem 2:

Algorithm:

 minDiffenceIndices(int[] A, int k)

Step 1: Create a HashTable

Step 2: Traverse the array and check if the Hash Table already contains the current element.

Step 3: if yes, then check if the difference between the current index of the element minus the previous index is less than equal to k, If yes print the current and previous index and return.

Step 4: Else keep on storing the array element with its current position.

Code:

import java.util.Hashtable;

public class Algorithm {
    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 2, 2, 5, 6, 3, 2, 7};
        minDiffenceIndices(arr, 6);

    }

    //Function to find the indices i and j such that A{i] = A[j] and j - i <= k
    public static void minDiffenceIndices(int[] A, int k) {
        int[] ans = {-1, -1};

        //Create a HashTable which can store Integer type keys and values
        Hashtable<Integer, Integer> map = new Hashtable<>();

        //Traverse the array
        for (int i = 0; i < A.length; i++) {

            //Check if an element is already stored as a key in the table
            if (map.containsKey(A[i])) {

                // If yes then check if the difference between the current index of the element
                // and the previous index is less than equal to k
                if (i - map.get(A[i]) <= k) {
                    ans[0] = map.get(A[i]);
                    ans[1] = i;
                    System.out.println(ans[0] + " " + ans[1]);
                    return;
                }
            }

            //Store the element with its current index in the hash table
            map.put(A[i], i);
        }
    }
}

import java.util.Hashtable; public class Algorithm { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 2, 2,

Output: We get the ouput 1 and 4 as 2 is present at 1 and 4 and K is equal to 6

14 Process finished with exit code @ —

Note: Both HashMap and HashTable can be used to solve the two problems, as both the data structures work in a similar way.

Add a comment
Know the answer?
Add Answer to:
Coded in Java. Also advised to use class java.util.HashMap Problem 1 You are given an array...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • the programming language is in java Problem 2 You are given an array A with n...

    the programming language is in java Problem 2 You are given an array A with n distinct elements. Implement an (n log n)-time algorithm that creates an array B where all elements are in range from 0 to n - 1 and where the order of elements is the same as in A. That is, 0 has the same index in B as the smallest element in A, 1 has the same index in B as the second smallest element...

  • Let A = [A[1], A[2],…..,A[n]] be an array of n distinct integers. For 1 <= j...

    Let A = [A[1], A[2],…..,A[n]] be an array of n distinct integers. For 1 <= j <= n, the index j is a happy index if A[i] < A[j] for all 1 <= i < j. Describe an O(n)- time algorithm that finds all the happy indices in the array A. Partial credit will be given for an O(n log(n))-time algorithm and a minimal credit will be given for an O(n^2) –time algorithm. What is the running time of your...

  • 1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array...

    1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array of distinct integers, and an integer x, return the index of x in the array. If the element x is not present in the array, return -1. "Almost sorted" means the following. Assume you had a sorted array A[0…N], and then split it into two pieces A[0…M] and A[M+1…N], and move the second piece upfront to get the following: A[M+1]…A[N]A[0]…A[M]. Thus, the "almost sorted"...

  • This should be in Java Create a simple hash table You should use an array for...

    This should be in Java Create a simple hash table You should use an array for the hash table, start with a size of 5 and when you get to 80% capacity double the size of your array each time. You should create a class to hold the data, which will be a key, value pair You should use an integer for you key, and a String for your value. For this lab assignment, we will keep it simple Use...

  • I need help with this in JAVA. please help me. Thank you. In this project. you...

    I need help with this in JAVA. please help me. Thank you. In this project. you are given a unimodal array of n integer and your task is to find the maximum integer in the array in theta(logn) time. An unimodal array of integers is an array with entries that monotonically increase up to the maximum integer value and then monotonically decrease for the rest of the array. For example: (2, 5, 8, 9, 12, 15, 21, 17, 10, 4)...

  • 1. a) Describe an O(m)-time algorithm that, given a set of S of n distinct numbers...

    1. a) Describe an O(m)-time algorithm that, given a set of S of n distinct numbers and a positive integer k c n, determines the top k numbers in s b) Describe an O(n)-time algorithm that, given a set of S of n distinct numbers and a positive integer k < n, determines the smallest k numbers in S.

  • the question from the course COMP 4040 that Analysis of Algorithms if you want to answer it by code please use C or C++...

    the question from the course COMP 4040 that Analysis of Algorithms if you want to answer it by code please use C or C++ 5. Algorithm Design (20 points) Input: array A contains n distinct numbers from 1 to n, in arbitrary order. Output: number of inversions (defined as the number of pair(i, j) of array indices with i < j and A[i] > Aj]) (a) (5 points) What array with elements from the set {1, 2, ..., n) has...

  • In Java, Implement a class MyArray as defined below, to store an array of integers (int)....

    In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion. Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another...

  • a. Use pseudocode to specify a brute-force algorithm that takes as input a list of n...

    a. Use pseudocode to specify a brute-force algorithm that takes as input a list of n positive integers and determines whether there are two distinct elements of the list that have as their sum a third element of the list. That is, whether there exists i, j.k such that iヂj, i关k,j关k and ai + aj = ak. The algorithm should loop through all triples of elements of the list checking whether the sum of the first two is the third...

  • Design and analysis of algorithms Type in answer Problem 5. Given a sorted array of distinct...

    Design and analysis of algorithms Type in answer Problem 5. Given a sorted array of distinct integers A[1- -n], you want to find out whether there is an index I for which Ai-i. Give a divide-and-conquer algorithm that runs in time O(log n)

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT