Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Array based question

The document contains various Java programs that demonstrate different array manipulations, including array rotation, finding the longest increasing subsequence, removing duplicates, counting frequencies, and finding pairs with specific conditions. Each section provides sample input and output, along with the corresponding Java code. The document serves as a tutorial for implementing common array operations and algorithms in Java.

Uploaded by

Ananya Samanta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Array based question

The document contains various Java programs that demonstrate different array manipulations, including array rotation, finding the longest increasing subsequence, removing duplicates, counting frequencies, and finding pairs with specific conditions. Each section provides sample input and output, along with the corresponding Java code. The document serves as a tutorial for implementing common array operations and algorithms in Java.

Uploaded by

Ananya Samanta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Array

1. Array rotation
Input: 3 4 5 6 7 3
Output: 5 6 7 3 4
//Iteration 1: 7 3 4 5 6
//Iteration 2: 6 7 3 4 5
//Iteration 3: 5 6 7 3 4
import java.util.*;
public class Main
{
static int[] function(int[] arr,int d){
ArrayList<Integer> l1=new ArrayList<>();
//Add array elements to arraylist
for(int i=0;i<arr.length;i++){
l1.add(arr[i]);
}
for(int i=0;i<d;i++){
int last=l1.remove(l1.size()-1);
l1.add(0,last);
}
//convert arraylist to array
int[] res=new int[l1.size()];
for(int i=0;i<l1.size();i++){
res[i]=l1.get(i);
}
return res;
}
public static void main(String[] args) {
System.out.println("Enter the size of array");
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
System.out.println("Enter the number of Iteration");
int d=sc.nextInt();
int ans[]=function(arr,d);
System.out.println(Arrays.toString(ans));
}
}

2. Input: 3 1 8 2 5 7 9
Output: 9 1 8 2 7 3 5
// Explanation : output Array contains: [largest element, smallest
element,second largest ,second smallest,third largest,third
smallest and so on………]
import java.util.*;
public class Main
{
static int[] function(int[] arr){
Arrays.sort(arr); // 1 2 3 5 7 8 9
ArrayList<Integer> l1=new ArrayList<>();
int first=0;
int last=arr.length-1;
while(first<=last){
if(first!=last){
l1.add(arr[last]);
l1.add(arr[first]);
}else{
l1.add(arr[last]);
}
first++;
last--;
}
//convert arraylist to array
int[] res=new int[l1.size()];
for(int i=0;i<l1.size();i++){
res[i]=l1.get(i);
}
return res;
}
public static void main(String[] args) {
System.out.println("Enter the size of array");
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
int ans[]=function(arr);
System.out.println(Arrays.toString(ans));
}
}
3. Wap to print the longest increasing subsequence in an array in java
Input: 10 22 9 33 21 50 41 60 80
Output: 10, 22, 33, 50, 60, 80
import java.util.*;
public class Main
{
static int[] function(int[] arr){
int max=0;
ArrayList<Integer> l1=new ArrayList<>();
for(int i=0;i<arr.length;i++){
if(arr[i]>max){
max=arr[i];
l1.add(max);
}
}
//convert arraylist to array
int[] res=new int[l1.size()];
for(int i=0;i<l1.size();i++){
res[i]=l1.get(i);
}
return res;
}
public static void main(String[] args) {
System.out.println("Enter the size of array");
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
int ans[]=function(arr);
System.out.println(Arrays.toString(ans));
}
}
4. Remove duplicate elements from an array/ print non-repeating
elements
import java.util.*;
class HelloWorld {
static int[] function(int[] arr){
HashSet<Integer> s1= new LinkedHashSet<>();//linked hashset because it
cannot change the insertion order
for(int num:arr){
s1.add(num);
}
int i=0;
int[] newarr=new int[s1.size()];
for(int ar:s1){
newarr[i++]=ar;
}
return newarr;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the array elements");
int[] a=new int[5];
for(int i=0;i<5;i++){
a[i]=sc.nextInt();
}
int[] ans=function(a);
System.out.println(Arrays.toString(ans));
}
}
//sum of non repeating elements in an array
import java.util.*;
class HelloWorld {
static int function(int[] arr){
HashSet<Integer> s1= new LinkedHashSet<>();//linked hashset because it
cannot change the insertion order
for(int num:arr){
s1.add(num);
}
int sum=0;
for(int ar:s1){
sum+=ar;
}
return sum;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the array elements");
int[] a=new int[5];
for(int i=0;i<5;i++){
a[i]=sc.nextInt();
}
int ans=function(a);
System.out.println(ans);
}
}
5. Print duplicate or repeating elements
import java.util.*;
public class Main
{
static int[] function(int[] arr){
HashSet<Integer> seen=new HashSet<>();
HashSet<Integer> duplicates=new HashSet<>();
for(int num:arr){
if(!seen.add(num)){
duplicates.add(num);
}
}
//convert hashset to array
int[] res=new int[duplicates.size()];
int i=0;
for(int n:duplicates){
res[i++]=n;
}
return res;
}
public static void main(String[] args) {
System.out.println("Enter the size of array");
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
int ans[]=function(arr);
System.out.println(Arrays.toString(ans));
}
}
6. Frequency of each element in an array
Output:
Element: 1 Frequency: 1
Element: 2 Frequency: 2
Element: 3 Frequency: 3
Element: 4 Frequency: 4
import java.util.*;
public class Main {
public static int[][] function(int[] arr) {
HashMap<Integer, Integer> m1 = new HashMap<>();
for (int i=0;i<arr.length;i++) {
if(m1.containsKey(arr[i])){
m1.put(arr[i],m1.get(arr[i])+1);//if the key is present then
increase the count by 1
}else{
m1.put(arr[i],1);//if the key not present then set count=1
}
}
// Convert HashMap to a 2D array(row*column)
int[][] farr = new int[m1.size()][2];
int i = 0;
for (Map.Entry<Integer, Integer> e : m1.entrySet()) {
farr[i][0] = e.getKey(); // element
farr[i][1] = e.getValue(); // frequency
i++;
}
return farr;
}
public static void main(String[] args) {
int[] array = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};

// Get the frequency array


int[][] ans = function(array);
for(int i=0;i<ans.length;i++){
System.out.println("Element: " + ans[i][0] + " Frequency: "
+ ans[i][1]);
}
}
}
//Easy way of hashmap iteration
import java.util.*;
public class Main {
public static void function(char[] arr) {
HashMap<Character, Integer> m1 = new HashMap<>();
// Count frequency of each element
for (int i=0;i<arr.length;i++) {
if(m1.containsKey(arr[i])){
m1.put(arr[i],m1.get(arr[i])+1);
}else{
m1.put(arr[i],1);
}
}
for (char key : m1.keySet()) {
System.out.println(key + " " + m1.get(key));
}
}
public static void main(String[] args) {
char[] array = {'a','b','c','d','b','b','c','c','d','d','d'};
function(array);
}
}

7. Print the element which frequency is maximum


Input: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4,4
Output: 4
import java.util.*;
public class Main {
public static void function(int[] arr) {
HashMap<Integer, Integer> m1 = new HashMap<>();
// Count frequency of each element
for (int i=0;i<arr.length;i++) {
if(m1.containsKey(arr[i])){
m1.put(arr[i],m1.get(arr[i])+1);
}else{
m1.put(arr[i],1);
}
}
// Find the maximum frequency
int maxFrequency = 0;
for (int freq : m1.values()) {
if (freq > maxFrequency) {
maxFrequency = freq;
}
}
for (int key : m1.keySet()) {
if (m1.get(key) == maxFrequency) {
System.out.println(key);
}
}
}
}
public static void main(String[] args) {
int[] array = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4,4};
function(array);
}
}
8. Find the majority elements in the array.Majority elements are the
elements which occurs more than or equal to N/2 times the
array.where N is the size of array.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<Integer,Integer> m1= new HashMap<>();
System.out.println("Enter the size of Array");
int size=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
int num=arr[i];
if(m1.containsKey(num)){
m1.put(num,m1.get(num)+1);
}else{
m1.put(num,1);
}
}
for(int number:m1.keySet()){
if(m1.get(number)>=size/2){
System.out.print(number);
}
}
}
}
9. Return an integer representing the count of pairs whoose avg is
present in the array
Input: 2 2 4 6
output: 3 [(2,2),(2,6) and (2,6)]
Input: 4 6 2
Output: 1 [[(6,2)]
import java.util.*;
class HelloWorld {
static int function(int[] arr){
HashSet<Integer> s1=new HashSet<>();
for(int num:arr){
s1.add(num);
}
int count=0;
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
int avg=(arr[i]+arr[j])/2;
if(s1.contains(avg)){
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length of array");
int size=sc.nextInt();
System.out.println("Enter the array elements");
int[] a=new int[size];
for(int i=0;i<size;i++){
a[i]=sc.nextInt();
}
int ans=function(a);
System.out.println(ans);
}
}
10. given an array and its size

find such pairs of integers whose sum is equal to 18


first element of the pair must be greater than the 2nd element
return the pair with maximum product value as an array
input:8
{11, 9, 13, 10, 8, 7, 4, 12}
output:{10, 8}
explanation: 8(size input)
from the input array, such pairs are {11, 7}, {10, 8}..[{7, 11} and {8,
10} are not valid pair because 7<11; 8<10]
Output:{10, 8}..because, 10*8>11*7

public class MaxProductPair {


public static int[] findMaxProductPair(int[] arr) {
int maxProduct = 0;
int[] result = new int[2]; // To store the pair with max product

// Iterate through the array to find valid pairs


for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
int first = arr[i];
int second = arr[j];

// Check if sum is 18 and the first element is greater than


the second
if (first + second == 18 && first > second) {
int product = first * second;
// Update the result if we found a greater product
if (product > maxProduct) {
maxProduct = product;
result[0] = first;
result[1] = second;
}
}
}
}

return result;
}

public static void main(String[] args) {


int[] arr = {11, 9, 13, 10, 8, 7, 4, 12};
int[] result = findMaxProductPair(arr);
System.out.println("Pair with maximum product: {" + result[0]
+ ", " + result[1] + "}");
}
}
11. Sliding Window Maximum (Maximum of all subarrays of size K)
Examples :
Input: arr[] = {1, 2, 3, 1, 4, 5}, K = 3
Output: 3 3 4 5
Explanation: Maximum of 1, 2, 3 is 3
Maximum of 2, 3, 1 is 3
Maximum of 3, 1, 4 is 4
Maximum of 1, 4, 5 is 5
Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4
Output: 10 10 10 15 15 90 90
public class GFG {
static void printKMax(int arr[], int N, int K)
{
int j, max;
for (int i = 0; i <= N - K; i++) {

max = arr[i];
for (j = 1; j < K; j++) {
if (arr[i + j] > max)
max = arr[i + j];
}
System.out.print(max + " ");
}
}

// Driver's code
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int K = 3;

// Function call
printKMax(arr, arr.length, K);
}
}
12. Union of two array
import java.util.*;
public class Union {
static int[] union(int[] arr1, int[] arr2) {
HashSet<Integer> set = new HashSet<>();
for (int i :arr1) {
set.add(i);
}
for (int j: arr2) {
set.add(j);
}
int[] ans=new int[set.size()];
int i=0;
for(int e:set) {
ans[i++]=e;
}
return ans;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of first array: ");
int size1 = sc.nextInt();
System.out.println("Enter first array elements");
int[] arr1=new int[size1];
for(int i=0;i<size1;i++){
arr1[i]=sc.nextInt();
}
System.out.print("Enter the size of second array: ");
int size2 = sc.nextInt();
System.out.println("Enter second array elements");
int[] arr2=new int[size2];
for(int i=0;i<size2;i++){
arr2[i]=sc.nextInt();
}
int ans[]=union(arr1,arr2);
System.out.println(Arrays.toString(ans));
}
}
//Intersection of two array
static int[] intersection(int[] arr1, int[] arr2) {
HashSet<Integer> set = new HashSet<>();
ArrayList<Integer> l1=new ArrayList<>();
for (int i :arr1) {
set.add(i);
}
for (int j: arr2) {
if(set.contains(j)){
l1.add(j);
set.remove(j);
}
}
int[] ans=new int[l1.size()];
int i=0;
for(int e:l1) {
ans[i++]=e;
}
return ans;
}
Sorting without inbuilt function Arrays.sort(arr1)
//Sort arr1 in ascending order
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
if(arr1[i]>arr1[j]){
int temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
//Sort arr2 in descending order
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
if(arr2[i]<arr2[j]){
int temp = arr2[i];
arr2[i] = arr2[j];
arr2[j] = temp;
}
}
}
13. Reversing array elements
import java.util.*;
public class Main
{
static int[] function(int[] arr,int n){

for(int i=0;i<n/2;i++){
int temp=arr[i];
arr[i]=arr[n-1-i];
arr[n-1-i]=temp;
}
return arr;
}
public static void main(String[] args) {
System.out.println("Enter the size of array");
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
int ans[]=function(arr,size);
for(int i=0;i<ans.length;i++){
System.out.print(ans[i]+ " ");
}
}
}
14. In a company there are employees and their efficiency is given in
array ‘arr’(can be negative).You need to find the maximum efficiency
of 3 employees will be calculated by multiplying their individual
efficiencies from the given array
Example 1: Input : 5, 3 -2 -8 4 1
Output:64

import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; ++i) {
arr[i] = scanner.nextInt();
}
Arrays.sort(arr);

// Max values
int emp1 = arr[N - 1];
int emp2 = arr[N - 2];
int emp3 = arr[N - 3];

// Negative case
int neg1 = arr[0];
int neg2 = arr[1];

System.out.println(Math.max(emp1 * emp2 * emp3, neg1 *


neg2 * emp1));
}
}
15. Subarray sum equal to k
Enter size
7
Enter array elements
5623143
Enter targetsum : 8
62
314
143
import java.util.*;
class A{
static void findSubarray(int arr[],int size,int targetSum){
HashMap<Integer,Integer> m1= new HashMap<>();
int currSum=0;
for(int i=0;i<size;i++){
currSum+=arr[i];
if(currSum==targetSum){
for(int j=0;j<=i;j++){
System.out.print(arr[j]+" ");
}
System.out.println();
}
if(m1.containsKey(currSum-targetSum)){
int startIdx=m1.get(currSum-targetSum)+1;
for(int k=startIdx;k<=i;k++){
System.out.print(arr[k]+" ");
}
System.out.println();
}
m1.put(currSum,i);
}
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter size");
int size=sc.nextInt();
int[] arr=new int[size];
System.out.println("Enter array elements");
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
System.out.println("Enter targetsum");
int targetSum=sc.nextInt();
findSubarray(arr,size,targetSum);
}
}
16. Find unique elements formed by taking bitwise OR between the
elements of different subarrays formed through an array.
import java.util.*;
class HelloWorld {
static int function(int arr[],int n){
HashSet<Integer> s1=new HashSet<>();
int sum=0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
sum=sum|arr[j];
s1.add(sum);
}
sum=0;
}
return s1.size();
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array");
int n=sc.nextInt();
System.out.println("Enter array elements");
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int ans=function(arr,n);
System.out.println(ans);
}
}
17. Enter no of terms
3
Apple 10.0 10
Orange 2.5 10
Apple 5.0 20
Output:
totalsale=225.0
avgsale=112.5
bestseller=Apple
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
HashMap<String,Double> m1=new HashMap<>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of terms");
int items=sc.nextInt();
double totalsale=0.0;
for(int i=0;i<items;i++){
String fruit=sc.next();
double unitcost=sc.nextDouble();
double quantity=sc.nextDouble();
double sale=(unitcost*quantity);
totalsale+=sale;
if(m1.containsKey(fruit)){
m1.put(fruit,m1.get(fruit)+sale);
}else{
m1.put(fruit,sale);
}
}
double bestsells=0.0;
String bestseller=" ";
for(String fru:m1.keySet()){
if(m1.get(fru)>bestsells){
bestsells=m1.get(fru);
bestseller=fru;
}
}
double avgsale=totalsale/m1.size();
System.out.println("totalsale=" + totalsale);
System.out.println("avgsale=" + avgsale);
System.out.println("bestseller=" + bestseller);
}
}
18. Count the pair of Shoes. pair means-(7L-7R) (5L-5R)
Enter the size of Array
9
Enter array elements
7L 8L 6R 6L 7L 8R 7R 7R 7R
4
Concept: LeftHashmap(L) RightHashmap(R)
Key val key val
7 2 6 1
8 1 8 1
6 1 7 3

import java.util.*;
class Main {
static int function(String[] arr){
HashMap<String,Integer> lm1 = new HashMap<>();
HashMap<String,Integer> rm1 = new HashMap<>();
for(String shoe:arr){
Character side=shoe.charAt(shoe.length()-1);
String size=shoe.substring(0,shoe.length()-1);
if(side=='L'){
if(lm1.containsKey(size)){
lm1.put(size,lm1.get(size)+1);
}else{
lm1.put(size,1);
}
}else if(side=='R'){
if(rm1.containsKey(size)){
rm1.put(size,rm1.get(size)+1);
}else{
rm1.put(size,1);
}
}
}
int pairCount=0;
for(String key :lm1.keySet()){
if(rm1.containsKey(key)){
pairCount+=Math.min(lm1.get(key),rm1.get(key));
}
}
return pairCount;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Array");
int size=sc.nextInt();
System.out.println("Enter array elements");
String[] arr=new String[size];
for(int i=0;i<size;i++){
arr[i]=sc.next();
}
int ans=function(arr);
System.out.println(ans);
}
}

You might also like