Search This Blog

Friday, October 8, 2021

GFG | DSA | School Level | Key note

Intellij Shortcuts Ctrl + / => comment or uncomment a line -> // Ctrl + shift + / => comment or uncomment block of code -> /**/ Ctrl + y => delete a line. Ctrl + d => duplicate a line. Reformat Code or press Ctrl+Alt+L 1----------- for reminder use % 2. ------- Single Line Print stmt use System.out.print("Hello World "); || System.out.println("Hello World "); 3 ------ Sum of elements in a 2D matrix int sumOfMatrix(int N, int M, int[][] Grid) { // code here int sum=0; for(int row=0;row 0){ int digit= N %10;// get digit one by one sum = sum+digit; N = N/10; //Remove last digit } return sum; } 6. ------------------- String to Lowe Case Using String Library approach 1 ------------------------ static String toLower(String S) { // code here return S.toLowerCase(); } ---------------- approach 2 Note:ASCII value of lowercase alphabets – 97 to 122. ASCII value of uppercase alphabets – 65 to 90 static String toLower(String S) { // Customised Code char [] charStr=S.toCharArray(); for(int i=0;i= 65 && (int) charStr[i] <=90){ charStr[i] = (char)((int)charStr[i]+32); } } return new String(charStr); } ------------------------------------------------mathematical ------------------------ 7. Swap two numbers Approach 1. static List get(int a,int b) { // code here int temp= a; a=b; b=temp; return Arrays.asList(a,b); } Approach 2. One line code static List get(int a,int b) { return Arrays.asList(b,a); } 8. ----------- Multiplication Table 9. -------- Odd WEven static String oddEven(int N){ // code here if(N %2 ==0) return "even"; else return "odd"; } 1o. ------ Find n-th term of series 1,3,6,10,15,21,….. These are all the sum of natural numbers upto the n So, in this series 1st Term = 1 2nd Term = 1+2 = 3 3rd Term = 1+2+3 = 6 4th Term = 1+2+3+4 = 10 So, Term - n = 1+2+3+….+n = n(n+1)/2 That’s your answer n(n+1)/2 Logic static int findNthTerm(int N) { int sumOfNaturalNumber=0; while (N >= 1){ sumOfNaturalNumber=sumOfNaturalNumber+N; N--; } return sumOfNaturalNumber; } 11. ArmstrongNum package com.java.hackerrank.GFG.mathematical; /** * @Author pankaj * @create 10/10/21 11:52 AM -------------------------- Oracle, VMWare ----------------------------------------- */ public class ArmstrongNum { static String armstrongNumber(int n) { // code here int temp = n; int sum = 0, digitCube = 1; while (temp > 0) { int digit = temp % 10; digitCube = digit * digit * digit; sum = sum + digitCube; temp = temp / 10; } if (sum == n) return "Yes"; else return "No"; } public static void main(String[] args) { System.out.println(ArmstrongNum.armstrongNumber(407)); } } 12. -------------- Reverse digits -------------- package com.java.hackerrank.GFG.mathematical; /** * @Author pankaj * @create 10/10/21 4:55 PM ------------- MAQ Software -----------------------------------*/ public class Reversedigits { public long reverse_digit(long n) { // Code here long digit, sum=0,temp =n; while (temp > 0){ digit =temp %10; sum = sum*10+digit; temp = temp/10; } return sum; } public static void main(String[] args) { System.out.print(new Reversedigits() .reverse_digit(200)); } } 13. ----------- Replace all 0's with 5 14. ---------- Sum of Series --------- return n*(n+1)/2;// need to validate 15. Sum of Digit is Pallindrome or not ---------------- Note:A Palindrome number is a number which stays the same when reversed.Example- 121,131,7 etc. package com.java.hackerrank.GFG.mathematical; /** * @Author pankaj * @create 10/13/21 5:51 PM --------------- SNAPDEAL -----------------*/ public class SumOfDigitIsPallindromeOrNot { int isDigitSumPalindrome(int N) { // code here // code for sum of digit int sum=0; while (N !=0){ int digit = N%10; sum = sum+digit; N= N/10; } // code for reverse number int sumOfDigit =sum; int reverse =0; while (sumOfDigit > 0){ int digit = sumOfDigit%10; reverse = reverse*10+digit; sumOfDigit= sumOfDigit/10; } if (sum == reverse) return 1; else return 0; } public static void main(String[] args) { System.out.println(new SumOfDigitIsPallindromeOrNot().isDigitSumPalindrome(56)); } } 16 . Greatest of three numbers Note: we must need to put = operator as wll to chek if nuimber is equal package com.java.hackerrank.GFG.mathematical; /** * @Author pankaj * @create 10/16/21 11:42 AM */ public class GreatestOfThreeNumbers { int greatestOfThree(int A, int B, int C) { // code here int great =0; if(A>=B && A>=C) great= A; else if (B >=A && B >= C) great= B; else great= C; return great; } public static void main(String[] args) { System.out.println(new GreatestOfThreeNumbers().greatestOfThree(0,1,5)); System.out.println(new GreatestOfThreeNumbers().greatestOfThree(10,2,3)); System.out.println(new GreatestOfThreeNumbers().greatestOfThree(550,1000,550000)); } } 17. Replace all 0's with 5 public static int convertFive(int n) { int sum = 0; for (int rank = 1; n > 0; n = n / 10, rank *= 10) { int digit = n % 10; if (digit == 0) digit = 5; sum = sum + digit * rank; } return sum; } 18. -------------------------- Automorphic Number A number is called Automorphic number if and only if its square ends in the same digits as the number itself. lOGIC package com.java.hackerrank.GFG.mathematical; /** * @Author pankaj * @create 10/19/21 1:39 PM */ public class AutomorphicNumber { public String is_AutomorphicNumber(int n) { // Code here int squareNum = n * n; while (n > 0) { //find the remainder (last digit) of the variable num and square and comparing them if (n % 10 != squareNum % 10) return "Not Automorphic"; //reduce num and square by dividing them by 10 n = n / 10; squareNum = squareNum / 10; } return "Automorphic"; } } 19. Compound Interest 20. Palindromic Array Given a Integer array A[] of n elements. Your task is to complete the function PalinArray. Which will return 1 if all the elements of the Array are palindrome otherwise it will return 0. public static int palinArray(int[] a, int n) { //add code here. // extract each element values // indexVal , check weather its palindromic or not // if all indexVal is palindromic // return 1, else return 0 for (int i = 0; i < a.length; i++) { int indexVal = a[i]; int sum = 0; while (indexVal > 0) { int lastDigit =indexVal%10; sum = sum * 10 + lastDigit; indexVal = indexVal / 10; } if (sum != a[i]) return 0; } return 1; 21. ---------------------------------- Largest number package com.java.hackerrank.GFG.Arrays; /** * @Author pankaj * @create 10/22/21 4:03 PM */ public class LargestNumber { int largestNumber(int arr[], int n) { // code here int i=0; int largest=0; while (i < n-1){ if (arr[i+1] < arr[i]){ arr[i+1] =arr[i]; largest =arr[i]; } i++; } return largest; } public static void main(String[] args) { System.out.println(new LargestNumber().largestNumber(new int[] {12, 35, 1, 10, 34, 1},6)); System.out.println(new LargestNumber().largestNumber(new int[] {10, 5, 10,66,100,600,05},7)); } } 22. --------------------- Second L:argest------------ VVI-- -------------------------------- Sap Labs, RockStand --------- public class SecondLargest { int print2largest(int arr[], int n) { // Approach ----------1 /*int temp; for (int i=0;i arr[j]){ temp = arr[i]; arr[i] =arr[j]; arr[j] =temp; } } } return arr[n-2];*/ // Approach-------------- 2 /* Arrays.sort(arr); return arr[n-2];*/ // Approach ------3 // code here int num=0; boolean c=true; if(n<2) return -1; Arrays.sort(arr); for(int i=n-2;i>=0;i--) { if(arr[i]!=arr[n-1]){ num=arr[i]; c=false; break; } } if(c) return -1; return num; } public static void main(String[] args) { System.out.println(new SecondLargest().print2largest(new int[] {12, 35, 1, 10, 34, 1},6)); System.out.println(new SecondLargest().print2largest(new int[] {10, 5, 10},3)); } } 23. -------------------- Reverse Array ---------------- package com.java.hackerrank.GFG.Arrays; /** * @Author pankaj * @create 10/23/21 9:34 AM */ public class PerfectArrays { public boolean IsPerfect(int a[], int n) { // Complete the function // reverse Array int[] revArray = new int[n]; int j = 0; for (int i = n - 1; i >= 0; i--) { revArray[j] = a[i]; j = j + 1; } // check a w.r.to revArray System.out.println("************** Rev ***************"); for (int rev : revArray) { System.out.print(rev + " "); } System.out.println(""); return true; } public static void main(String[] args) { new PerfectArrays().IsPerfect(new int[]{1, 2, 3, 2, 1}, 5); new PerfectArrays().IsPerfect(new int[]{1, 2, 3, 4, 5}, 5); new PerfectArrays().IsPerfect(new int[]{11, 12, 14, 12, 19, 11}, 6); } } 24. -------------------- PerfectArrays -------------- Input : Arr[] = {1, 2, 3, 2, 1} Output : PERFECT Explanation: Here we can see we have [1, 2, 3, 2, 1] if we reverse it we can find [1, 2, 3, 2, 1] which is the same as before. So, the answer is PERFECT. package com.java.hackerrank.GFG.Arrays; /** * @Author pankaj * @create 10/23/21 9:34 AM */ public class PerfectArrays { public boolean IsPerfect(int a[], int n) { // Complete the function // reverse Array int[] revArray = new int[n]; int j = 0; for (int i = n - 1; i >= 0; i--) { revArray[j] = a[i]; j = j + 1; } // check a w.r.to revArray boolean isPerfect = false; int count = 0; for (int i = 0; i < n; i++) { if (a[i] == revArray[i]) count = count+1; } if (count ==n ) isPerfect = true; return isPerfect; } public static void main(String[] args) { System.out.println(new PerfectArrays().IsPerfect(new int[]{1, 2, 3, 2, 1}, 5)); System.out.println(new PerfectArrays().IsPerfect(new int[]{1, 2, 3, 4, 5}, 5)); System.out.println(new PerfectArrays().IsPerfect(new int[]{11, 12, 14, 12, 19, 11}, 6)); } } 25. ----------------- JavaArraysAverage1 --> calculate the average of all prices upto 2 decimal places. Hint: You can use the printf method, like so: String.format("%.2f",number); String average(int A[], int N) { double sum=0; int i=0; while (i hm, int x, int y) { //Your code here hm.put(x,y); } /*Returns the value with key x from the map */ int find_value(HashMap hm, int x) { //Your code here** if (hm.containsKey(x)) return hm.get(x); else return -1; } /*Returns the size of the map */ int getSize(HashMap hm) { //Your code here return hm.size(); } /*Removes the entry with key x from the map */ void removeKey(HashMap hm, int x) { //Your code here hm.remove(x); } } 36. ------------------------ TreeMapOperations ---------------- import java.util.Collections; import java.util.TreeMap; /** * @Author pankaj * @create 10/30/21 11:52 AM Implement different operations on Treemap. Operations will be performed by different types of queries. A query can be of four types: 1. a x y (adds an entry with key x and value y to the Treemap) 2. b x (print value of x if present in the Treemap else print -1. ) 3. c (prints the size of the Treemap) 4. d x ( removes an entry with key x from the map ) 5. e (print map sorted by key) Example 1: Input: 6 a 1 2 a 66 3 b 66 d 1 c e Output: 3 1 66 Explanation: There are five queries. Queries are performed in this order 1. a 1 2 ---> map has a key 1 with value 2 2. a 66 3 ---> map has a key 66 with value 3 3. b 66 ---> prints the value of key 66 if its present in the map ie 3. 4. d 1 ---> removes an entry from map with key 1 5. c ---> prints the size of the map ie 1 6. e ---> prints the map sorted by key */ public class TreeMapOperations { /*Inserts an entry with key x and value y in map */ void add_Value(TreeMap hm, int x, int y) { //Your code here hm.put(x,y); } /*Returns the value with key x from the map */ int find_value(TreeMap hm, int x){ //Your code here if (hm.containsKey(x)) return hm.get(x); else return -1; } /*Returns the size of the map */ int getSize(TreeMap hm) { //Your code here return hm.size(); } /*Removes the entry with key x from the map */ void removeKey(TreeMap hm, int x) { //Your code here hm.remove(x); } /*print map sorted by key */ void sorted_By_Key(TreeMap hm) { // Your code here for (Integer treeKey : hm.keySet()){ System.out.print(treeKey+" "); } } } 37. -------------------------- HashMap ----------------------- HashMap is a part of collection in Java. It provides the basic implementation of Map interface of Java. It stores the data in (Key, Value) pairs. To access a value you must know its key, otherwise, you can’t access it. HashMap is known as HashMap because it uses the technique called Hashing. Solve the following problem using a HashMap. Given two arrays key[] and arr[] of size N and a key s. Each key[i] and arr[i] form a key-value pair. Find if the value of S in the N key-value pairs. Example 1: Input: n = 3 keys = {sak, varun, vijay} arr = {5, 7, 3} s = sak Output: 5 Explaination: The key is present in the map. So its corresponding value is returned which is 5. Example 2: Input: n = 4 keys = {csdb, dsh, askj, adfs} arr = {4, 5, 8, 9} s = dptu Output: -1 Explaination: The key is not present in the map. Your Task: You do not need to read input or print anything. Yous task is to complete the function map() which takes n, keys[], arr[] and s as input parameters and returns the value associated with the key s. If the key is not present return -1. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1) Constraints: 1 ≤ n, |length of key|, value ≤ 1000 ========================== Pair class======================================================================================= Core Java Implementation 2.1. The Pair Class We can find the Pair class in the javafx.util package. The constructor of this class takes two arguments, a key and its corresponding value: Pair pair = new Pair<>(1, "One"); Integer key = pair.getKey(); String value = pair.getValue(); This example illustrates a simple Integer to String mapping using the Pair concept. As shown, the key in the pair object is retrieved by invoking a getKey() method, while the value is retrieved by calling getValue(). 2.2. AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry SimpleEntry is defined as a nested class inside the AbstractMap class. To create an object of this type we can provide a key and value to the constructor: AbstractMap.SimpleEntry entry = new AbstractMap.SimpleEntry<>(1, "one"); Integer key = entry.getKey(); String value = entry.getValue(); The key and value can be accessed through standard getter and setter methods. Additionally, the AbstractMap class also contains a nested class that represents an immutable pair, the SimpleImmutableEntry class: AbstractMap.SimpleImmutableEntry entry = new AbstractMap.SimpleImmutableEntry<>(1, "one"); This works in a similar way to the mutable pair class, except the value of the pair cannot be changed. Attempting to do so will result in an UnsupportedOperationException. 3. Apache Commons In the Apache Commons library, we can find the Pair class in the org.apache.commons.lang3.tuple package. This is an abstract class, so it cannot be instantiated directly. Here we can find two sub-classes representing immutable and mutable pairs, ImmutablePair and MutablePair. Both implementations have access to key/value getter/setter methods: ImmutablePair pair = new ImmutablePair<>(2, "Two"); Integer key = pair.getKey(); String value = pair.getValue(); Unsurprisingly, an attempt to invoke setValue() on the ImmutablePair results in an UnsupportedOperationException. However, the operation is entirely valid for a mutable implementation: Pair pair = new MutablePair<>(3, "Three"); pair.setValue("New Three"); 4. Vavr In the Vavr library, the pair functionality is provided by the immutable Tuple2 class: Tuple2 pair = new Tuple2<>(4, "Four"); Integer key = pair._1(); String value = pair._2(); In this implementation, we can't modify the object after creation, so mutating methods are returning a new instance that includes the provided change: tuplePair = pair.update2("New Four"); 5. Alternative I – Simple Container Class Either by user preference or in the absence of any of the aforementioned libraries, a standard workaround for the pair functionality is creating a simple container class that wraps desired return values. The biggest advantage here is an ability to provide our name, which helps in avoiding having the same class representing different domain objects: public class CustomPair { private String key; private String value; // standard getters and setters } 6. Alternative II – Arrays Another common workaround is by using a simple array with two elements to achieve similar results: private Object[] getPair() { // ... return new Object[] {key, value}; } Typically, the key is located at index zero of the array, while its corresponding value is located at index one. ========================================================================================================================= 38. ------------- Reverse sub array void reverseSubArray(int arr[], int n, int l, int r) { // code here int leftIndex = l-1,rightIndex =r-1; while (leftIndex alternateSort(long arr[] , int N) { // Your code goes here ArrayList arrayList=new ArrayList<>(); Arrays.sort(arr); int k=0; for (int i=0;i0;j--){ insert(arr,j); } } } } ====== 41. --------------------------- STACK --------------------------- package com.java.hackerrank.ForkJava.MOdule4; import java.util.Stack; /** * @Author pankaj * @create 11/20/21 5:29 PM * This Java module deals with Stacks, Queues, and ArrayLists. We'll perform various operations on them. *

* Given a stack of integers and Q queries. The task is to perform operation on stack according to the query. *

* Note: use push() to add element in the stack, peek() to get topmost element without removal, pop() gives topmost element with removal, search() to return position if found else -1. *

* Input Format: * First line of input contains nubmer of testcases T. For each testcase, first line of input contains Q, number of queries. Next line contains Q queries seperated by space. Queries are as: *

* i x : (adds element x in the stack). *

* r : (returns and removes the topmost element from the stack). *

* h : Prints the topmost element. *

* f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No". *

* Output Format: * For each testcase, perform Q queries and print the output wherever required. *

* Your Task: * Your task is to complete functions insert(), remove(), headOf_Stack() and find(), to insert, remove returning top element and findiing the elment in stack respectively. *

* Constraints: * 1 <= T <= 100 * 1 <= Q <= 103 *

* Example: * Input: * 2 * 6 * i 2 i 4 i 3 i 5 h f 8 * 4 * i 3 i 4 r f 3 *

* Output: * 5 * No * Yes *

* Explanation: * Testcase 1: Inserting 2, 4, 3, and 5 onto the stack. Returning top element which is 5. Finding 8 will give No, as 8 is not in the stack. */ public class StackOperations { // Function to insert element to stack public static void insert(Stack st, int x) { // Your code here st.push(x); } // Function to pop element from stack public static void remove(Stack st) { int x = st.pop(); } // Function to return top of stack public static void headOf_Stack(Stack st) { int x = st.peek(); System.out.println(x + " "); }package com.java.hackerrank.ForkJava.MOdule4; import java.util.Stack; /** * @Author pankaj * @create 11/20/21 5:29 PM * This Java module deals with Stacks, Queues, and ArrayLists. We'll perform various operations on them. *

* Given a stack of integers and Q queries. The task is to perform operation on stack according to the query. *

* Note: use push() to add element in the stack, peek() to get topmost element without removal, pop() gives topmost element with removal, search() to return position if found else -1. *

* Input Format: * First line of input contains nubmer of testcases T. For each testcase, first line of input contains Q, number of queries. Next line contains Q queries seperated by space. Queries are as: *

* i x : (adds element x in the stack). *

* r : (returns and removes the topmost element from the stack). *

* h : Prints the topmost element. *

* f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No". *

* Output Format: * For each testcase, perform Q queries and print the output wherever required. *

* Your Task: * Your task is to complete functions insert(), remove(), headOf_Stack() and find(), to insert, remove returning top element and findiing the elment in stack respectively. *

* Constraints: * 1 <= T <= 100 * 1 <= Q <= 103 *

* Example: * Input: * 2 * 6 * i 2 i 4 i 3 i 5 h f 8 * 4 * i 3 i 4 r f 3 *

* Output: * 5 * No * Yes *

* Explanation: * Testcase 1: Inserting 2, 4, 3, and 5 onto the stack. Returning top element which is 5. Finding 8 will give No, as 8 is not in the stack. */ public class StackOperations { // Function to insert element to stack public static void insert(Stack st, int x) { // Your code here st.push(x); } // Function to pop element from stack public static void remove(Stack st) { int x = st.pop(); } // Function to return top of stack public static void headOf_Stack(Stack st) { int x = st.peek(); System.out.println(x + " "); } // Function to find the element in stack public static void find(Stack st, int val) { if (st.search(val)!=-1) { System.out.println("Yes"); } else { System.out.println("No"); } } } // Function to find the element in stack public static void find(Stack st, int val) { if (st.search(val)!=-1) { System.out.println("Yes"); } else { System.out.println("No"); } } } 42. ----------------------------------------- Queue operation -------------------------------------- package com.java.hackerrank.ForkJava.MOdule4; import java.util.Queue; /** * @Author pankaj * @create 11/20/21 6:39 PM Here, we will learn operations on queues. Given N integers, the task is to insert those elements in the queue. Also, given M integers, task is to find the frequency of each number in the Queue. Example: Input: 8 1 2 3 4 5 2 3 1 5 1 3 2 9 10 Output: 2 2 2 -1 -1 Explanation: After inserting 1, 2, 3, 4, 5, 2, 3, 1 into the queue, frequency of 1 is 2, 3 is 2, 2 is 2, 9 is -1 and 10 is -1 (since, 9 and 10 is not there in the queue). Your Task: Your task is to complete the functions insert() and findFrequency() which inserts the element into the queue and find the count of occurences of element in the queue respectively. */ public class QueueOperations { // Function to insert element into the queue static void insert(Queue q, int k){ // Your code here q.add(k); } // Function to find frequency of an element // rteturn the frequency of k static int findFrequency(Queue q, int k){ // Your code here int count =0; for (int i=0;i q, int k){ // Your code here //Just insert k in q and don't return anything q.add(k); } // Function to find an element k static boolean find(PriorityQueue q, int k){ // Your code here // If k is in q return true else return false if (q.contains(k)) return true; else return false; } // Function to delete the max element from queue static int delete(PriorityQueue q){ // Your code here //Delete the max element from q. The priority queue property might be useful here return q.poll(); } } 44. ---------------------------------------------- ArrayList Operation --------------------------------- Given an ArrayList of N lowercase characters. The task is to count frequency of elements in the list. Note: use add() to append element in the list and contains() to check an element is present or not in the list and collections.frequency() to find the frequency of the element in the list. Input Format: First line of testcase contains T, number of testcases. For each testcase, first line contains number of queries Q. Each query may be any one of the two type: 1. "i" with "c" : insert the element "c" into the ArrayList 2. "f" with "c": find the frequency of "c" in the ArrayList. Output Format: For each testcase, output the frequency of elements. Print "Not Present" if element is not present in the list else its frequency in new line for every query. Your Task: Your task is to complete the functions insert() and freq() which are used to insert and find frequency of element respectively. Constraints: 1 <= T <= 100 1 <= N <= 105 1 <= Q <= 102 Example: Input: 2 6 i g i e i e i k i s f e 4 i c i p i p f f Output: 2 Not Present Explanation: Testcase 1: Inserting g, e, e, k, s into the list. Frequency of e is 2 in the list. Testcase 2: Inserting c, p, p into the list. Frequency of f is 0 in the list. public class ArrayListOperation { // Function to insert element public static void insert(ArrayList clist, char c) { //add c to clist clist.add(c); } // Function to count frequency of element public static void freq(ArrayList clist, char c) { if(clist.contains(c)) System.out.println(Collections.frequency(clist,c)); else System.out.println("Not Present"); } } 45. ---------------------------------- Operations on ArrayList ------------------------------------- package com.java.hackerrank.ForkJava.MOdule4; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * @Author pankaj * @create 11/20/21 7:35 PM * Given an arraylist of integers. The task is to perform operations on ArrayList according to the queries and print output for the required queries. *

* Note: use Collections.sort() to sort the list in natural order, Collections.reverseOrder() to arrange the elements in reverse, get() to return the element at index of the list, binarySearch() to find the index of the specified element in the list. *

* Input Format: * First line of input contains number of testcase T. For each testcase, first line of input contains Q, number of queries. Next line contains Q queries as: *

* a x : inserts the element x at the end of the list. *

* i : arrange the list in increasing order. *

* d : arrange the list in decreasing order. *

* s y : search for the element y in the list and prints the first-index(for duplicate) (0-based indexing) of that in the list. -1 if not found. *

* Output Format: * For each testcase, print the output according to the queries. *

* Your Task: * Your task is to complete the functions insert(), IncOrder(), Search() and DecOrder() such that driver code will be able to perform required queries. *

* Constraints: * 1 <= T <= 100 * 1 <= A[i] <= 106 * 1 <= Q <= 103 *

* Example: * Input: * 2 * 6 * a 2 a 3 a 4 a 2 i s 2 * 5 * a 2 a 3 a 3 d s 5 *

* Output: * 0 * -1 *

* Explanation: * Testcase 1: After inserting elements, list is (2, 3, 4, 2) and arranging them in ascending order, we have list as (2, 2, 3, 4). Now, serching for 2, first occurence is at 0th index. *

* Testcase 2: After inserting elements, list is (2, 3, 3) and arranging them in descending order, we have list as (3, 3, 2). Finding 5 gives -1, as 5 is not present. */ public class OperationsOnArrayList { // Function to insert element into list public static void insert(ArrayList list, int x) { // Your code here list.add(x); } // Function to sort list in Increasing order public static void IncOrder(ArrayList list) { // Your code here Collections.sort(list); } // Function to search element in the lise // val : element to be searched public static void Search(ArrayList list, int val) { int flag=-1; Collections.sort(list); if(list.contains(val)) flag=list.indexOf(val); if(flag==-1){ System.out.println(flag);} else{ System.out.println(flag);} } // Function to sort list in decreasing order public static void DecOrder(ArrayList list) { // Your code here Collections.sort(list,Collections.reverseOrder()); } } 46. --------------------------------------------