The post Special Palindrome Again Challenge appeared first on fizzbuzzer.com.
]]>aaa
.aadaa
.
A specialpalindromic substring is any substring of a string which meets one of those criteria. Given a string, determine how many special palindromic substrings can be formed from it.
For example, given the string s=mnonopoo
, we have the following special palindromic substrings: {m, n, o, n, o, p, o, o, non, ono, opo, oo}
.
Function Description
Complete the substrCount
function. It should return an integer representing the number of special palindromic substrings that can be formed from the given string.
substrCount
has the following parameter(s):
* n
: an integer, the length of string s
* s
: a string
Input Format
The first line contains an integer, n
, the length of s
.
The second line contains the string s
.
Constraints
*
* Each character of the string is a lowercase alphabet, ascii[a-z]
.
Sample Input 0
5 asasd
Sample Output 0
7
Explanation 0
The special palindromic substrings of s=asasd
are {a, s, a, s, d, asa, sas}
.
Solution
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; public class SpecialPalindromeAgain { static Map<String, Long> bruteforce(int n, String s) { Map<String, Long> result = new HashMap<>(); for (int i = 0; i < n; i++) { for (int len = 1; len <= n - i; len++) { String substr = s.substring(i, i + len); if (substr.length() == 1) { if (!result.containsKey(substr)) { result.put(substr, 0l); } result.put(substr, result.get(substr) + 1); } else if (substr.length() > 0 && substr.length() % 2 == 0) { boolean allSame = true; for (int j = 1; j < substr.length(); j++) { if (substr.charAt(j) != substr.charAt(j - 1)) { allSame = false; break; } if (allSame) { if (!result.containsKey(substr)) { result.put(substr, 0l); } result.put(substr, result.get(substr) + 1); } } } else if (substr.length() > 0 && substr.length() % 2 == 1) { int mid = substr.length() / 2; String left = substr.substring(0, mid); String right = substr.substring(mid + 1); if (left.equals(right)) { if (!result.containsKey(substr)) { result.put(substr, 0l); } result.put(substr, result.get(substr) + 1); } } } } return result; } static long substrCount(int n, String s) { long ans = 0; for (int i = 0; i < n; i++) { ans++; char previousChar = s.charAt(i); int charsLeftCount = 1; int charsRightCount = 0; boolean reachedMiddle = false; for (int j = i + 1; j < n; j++) { char ch = s.charAt(j); if (!reachedMiddle && ch != previousChar) { reachedMiddle = true; } else if (reachedMiddle && (ch != previousChar || j == n - 1)) { if (j == n - 1 && ch == previousChar) { charsRightCount++; } if (charsLeftCount == charsRightCount) { ans++; } break; } else if (!reachedMiddle && ch == previousChar) { charsLeftCount++; if (charsLeftCount >= 2) { ans++; } } else if (reachedMiddle && ch == previousChar) { charsRightCount++; if (charsLeftCount == charsRightCount) { ans++; break; } } } } return ans; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in3.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String s = scanner.next(); long startTime = System.currentTimeMillis(); long result = substrCount(n, s); long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + " ms"); Scanner expectedScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "expected3.txt")); long expected = expectedScanner.nextLong(); if (result != expected) { System.out.println("Error: expected " + expected + " got " + result); } else { System.out.println("Correct: expected " + expected + " got " + result); } } }
The post Special Palindrome Again Challenge appeared first on fizzbuzzer.com.
]]>The post Making Anagrams Challenge appeared first on fizzbuzzer.com.
]]>Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?
Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings.
For example, if and , we can delete from string and from string so that both remaining strings are and which are anagrams.
Function Description
Complete the makeAnagram
function in the editor below. It must return an integer representing the minimum total characters that must be deleted to make the strings anagrams.
makeAnagram
has the following parameter(s):
a
: a string
b
: a string
Input Format
The first line contains a single string, .
The second line contains a single string, .
Constraints
*
* The strings and consist of lowercase English alphabetic letters ascii[a-z].
Output Format
Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.
Sample Input
cde abc
Sample Output
4
Explanation
We delete the following characters from our two strings to turn them into anagrams of each other:
1. Remove and from to get .
2. Remove and from to get .
We must delete characters to make both strings anagrams, so we print on a new line.
Solution
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class MakingAnagrams { static int makeAnagram(String a, String b) { int ans = 0; int[] countA = new int[26]; int[] countB = new int[26]; // Map chars to count for (int i = 0; i < a.length(); i++) { char ch = a.charAt(i); countA[ch - 'a'] += 1; } for (int i = 0; i < b.length(); i++) { char ch = b.charAt(i); countB[ch - 'a'] += 1; } for (int i = 0; i < countA.length; i++) { if (countA[i] > countB[i]) { ans += (countA[i] - countB[i]); } else if (countB[i] > countA[i]) { ans += (countB[i] - countA[i]); } } return ans; } public static void main(String[] args) throws FileNotFoundException { long startTime = System.currentTimeMillis(); System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt")); Scanner scanner = new Scanner(System.in); String a = scanner.nextLine(); String b = scanner.nextLine(); int result = makeAnagram(a, b); long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + " ms"); System.out.println(result); } }
The post Making Anagrams Challenge appeared first on fizzbuzzer.com.
]]>The post Counting Inversions Challenge appeared first on fizzbuzzer.com.
]]>For example, consider the dataset . It has two inversions: and . To sort the array, we must perform the following two swaps to correct the inversions:
Given datasets, print the number of inversions that must be swapped to sort each dataset on a new line.
Function Description
Complete the function countInversions
in the editor below. It must return an integer representing the number of inversions required to sort the array.
countInversions
has the following parameter(s):
* arr
: an array of integers to sort.
Input Format
The first line contains an integer, , the number of datasets.
Each of the next pairs of lines is as follows:
1. The first line contains an integer, , the number of elements in .
Constraints
*
*
*
Output Format
For each of the datasets, return the number of inversions that must be swapped to sort the dataset.
Sample Input 1
2 5 1 1 1 2 2 5 2 1 3 1 2
Sample Output 1
0 4
Explanation
We sort the following datasets:
1. is already sorted, so there are no inversions for us to correct. Thus, we print on a new line.
2.
We performed a total of swaps to correct inversions.
Sample Input 2
1 5 2 1 0 3 0
Sample Output 2
6
Solution
I will use Sample Input 2 as my solution sample input. The solution can be found in time.
The way I approach this problem is by first implementing the Merge Sort algorithm to sort the input array. The recursion tree for looks as follows:
Starting from the bottom of the tree, once the array can no longer be split, the arrays (left and right in red color) will be merged at each level of the tree:
Comparing each of the left and right sorted array (red) at each level we can see that the number of swaps we need to make is:
“the sum of counts of right items that are smaller than the current left item for each left item”. For example, comparing and we count for left item since . We also count for left item since . This is because we need to swap those pairs in order to sort the array. We do this at all levels to calculate the number of total swaps.
We can do this count during the merging of or left and right array. What we do is follows:
1. Once we stumble upon a left item that is larger than our right item, we set a flag that we need to start counting.
2. If the left item is again less than or equal to a right item and we started our count earlier, then the number of items smaller than our previous left (the one were we started our count) must be equal to the current rightCursor
in the right array. The later is because we know the left/right arrays are sorted and any left item will also be . The same goes for any subsequent left item that is (See comparison and ).
Finally, for any items left in the left array, we need to add , since each one of these left items is greater than all items in the right array.
Code
package problems; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; public class NumberOfInversions { static long count = 0; static void merge(int[] arr, int low, int mid, int high) { int leftArraySize = mid - low + 1; int rightArraySize = high - mid; int[] left = Arrays.copyOfRange(arr, low, mid + 1); int[] right = Arrays.copyOfRange(arr, mid + 1, high + 1); int cursorLeft = 0; int cursorRight = 0; int arrCursor = low; boolean isCounting = false; int lastLeftItemForWhichWeCounted = -1; while (cursorLeft < leftArraySize && cursorRight < rightArraySize) { if (left[cursorLeft] <= right[cursorRight]) { if (isCounting || (lastLeftItemForWhichWeCounted != -1 && left[cursorLeft] >= lastLeftItemForWhichWeCounted)) { count += cursorRight; isCounting = false; } arr[arrCursor] = left[cursorLeft]; cursorLeft++; } else { arr[arrCursor] = right[cursorRight]; if (!isCounting) { isCounting = true; lastLeftItemForWhichWeCounted = left[cursorLeft]; } cursorRight++; } arrCursor++; } while (cursorLeft < leftArraySize) { arr[arrCursor] = left[cursorLeft]; count += rightArraySize; cursorLeft++; arrCursor++; } while (cursorRight < rightArraySize) { arr[arrCursor] = right[cursorRight]; cursorRight++; arrCursor++; } } static void mergeSort(int[] arr, int low, int high) { if (low < high) { int mid = (low + high) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } } static long countInversions(int[] arr) { count = 0; mergeSort(arr, 0, arr.length - 1); return count; } public static void main(String[] args) throws FileNotFoundException { long startTime = System.currentTimeMillis(); System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in4.txt")); Scanner scanner = new Scanner(System.in); int d = scanner.nextInt(); long[] answers = new long[d]; for (int i = 0; i < d; i++) { int n = scanner.nextInt(); int[] arr = new int[n]; for (int j = 0; j < n; j++) { arr[j] = scanner.nextInt(); } long ans = countInversions(arr); answers[i] = ans; } long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + " ms"); /* Verify Results */ Scanner resultScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "expected4.txt")); int cursor = 0; boolean correct = true; for (int i = 0; i < d; i++) { long expected = resultScanner.nextLong(); if (expected != answers[i]) { System.out.println("Expected " + expected + " got " + answers[i]); correct = false; break; } } if (correct) { System.out.println("Correct"); } else { System.out.println("Error"); } } }
The post Counting Inversions Challenge appeared first on fizzbuzzer.com.
]]>The post Frequency Queries appeared first on fizzbuzzer.com.
]]>The queries are given in the form of a 2-D array queries
of size where queries[i][0]
contains the operation, and queries[i][1]
contains the data element. For example, you are given array . The results of each operation are:
Operation Array Output (1,1) [1] (2,2) [1] (3,2) 0 (1,1) [1,1] (1,1) [1,1,1] (2,1) [1,1] (3,2) 1
Return an array with the output: .
Function Description
Complete the freqQuery
function. It must return an array of integers where each element is a if there is at least one element value with the queried number of occurrences in the current array, or if there is not.
freqQuery
has the following parameter(s):
Input Format
The first line contains of an integer , the number of queries.
Each of the next lines contains two integers denoting the 2-d array .
Constraints
*
*
* All
* All
Output Format
Return an integer array consisting of all the outputs of queries of type .
Sample Input 0
8 1 5 1 6 3 2 1 10 1 10 1 6 2 5 3 2
Sample Output 0
0 1
Solution
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { static List<Integer> freqQuery(List<Integer[]> queries) { List<Integer> ans = new ArrayList<>(); final int INSERT = 1; final int REMOVE = 2; final int QUERY = 3; Map<Integer, Integer> value2count = new HashMap<>(); Map<Integer, Integer> count2countOccurance = new HashMap<>(); for (Integer[] q: queries) { int type = q[0]; int value = q[1]; if (type == INSERT) { if (value2count.containsKey(value)) { int oldCount = value2count.get(value); int newCount = oldCount + 1; value2count.put(value, newCount); count2countOccurance.put(oldCount, count2countOccurance.get(oldCount) - 1); if (!count2countOccurance.containsKey(newCount)) { count2countOccurance.put(newCount, 0); } count2countOccurance.put(newCount, count2countOccurance.get(newCount) + 1); } else { value2count.put(value, 1); if (!count2countOccurance.containsKey(1)) { count2countOccurance.put(1, 0); } count2countOccurance.put(1, count2countOccurance.get(1) + 1); } } else if (type == REMOVE) { if (value2count.containsKey(value)) { int oldCount = value2count.get(value); int newCount = Math.max(oldCount - 1, 0); value2count.put(value, newCount); count2countOccurance.put(oldCount, count2countOccurance.get(oldCount) - 1); if (!count2countOccurance.containsKey(newCount)) { count2countOccurance.put(newCount, 0); } count2countOccurance.put(newCount, count2countOccurance.get(newCount) + 1); } } else if (type == QUERY) { if (count2countOccurance.containsKey(value) && count2countOccurance.get(value) > 0) { ans.add(1); } else { ans.add(0); } } } return ans; } public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int q = Integer.parseInt(bufferedReader.readLine().trim()); List<Integer[]> queries = new ArrayList<>(); for (int i = 0; i < q; i++) { String[] queriesRowTempItems = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); Integer[] queriesRowItems = new Integer[2]; queriesRowItems[0] = Integer.parseInt(queriesRowTempItems[0]); queriesRowItems[1] = Integer.parseInt(queriesRowTempItems[1]); queries.add(queriesRowItems); } List<Integer> ans = freqQuery(queries); for (int i = 0; i < ans.size(); i++) { bufferedWriter.write(String.valueOf(ans.get(i))); if (i != ans.size() - 1) { bufferedWriter.write("\n"); } } bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
The post Frequency Queries appeared first on fizzbuzzer.com.
]]>The post Count Triplets Challenge appeared first on fizzbuzzer.com.
]]>For example, . If , we have and at indices and .
Function Description
Complete the countTriplets function in the editor below. It should return the number of triplets forming a geometric progression for a given as an integer. countTriplets has the following parameter(s):
* arr
: an array of integers
* r
: an integer, the common ratio
Input Format
The first line contains two space-separated integers and , the size of and the common ratio.
The next line contains space-seperated integers .
Constraints
*
*
*
Output Format
Return the count of triplets that form a geometric progression.
Sample Input 0
4 2 1 2 2 4
Sample Output 0
2
Explanation 0
There are triplets in satisfying our criteria, whose indices are and
Sample Input 1
6 3 1 3 9 9 27 81
Sample Output 1
6
Explanation 1
The triplets satisfying are index , , , , and .
Solution
package problems; package problems; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class CountTriplets { static long countTriplets(Listarr, long r) { long ans = 0; Long[] array = new Long[arr.size()]; Map right = new HashMap (); Map left = new HashMap (); for (int i = 0; i < arr.size(); i++) { array[i] = arr.get(i); right.put(array[i], 0l); left.put(array[i], 0l); } for (int i = 0; i < array.length; i++) { Long num = array[i]; right.put(num, right.get(num) + 1); } for (int i = 0; i < array.length; i++) { Long num2 = array[i]; right.put(num2, right.get(num2) - 1); if (num2 % r == 0) { Long num1 = num2 / r; Long num3 = num2 * r; if (left.containsKey(num1) && right.containsKey(num3)) { ans += (left.get(num1) * right.get(num3)); } } left.put(num2, left.get(num2) + 1); } return ans; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in_166661666700000_2.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int r = scanner.nextInt(); List arr = new LinkedList<>(); for (int i = 0; i < n; i++) { arr.add(scanner.nextLong()); } System.out.println(countTriplets(arr, r)); } }
The post Count Triplets Challenge appeared first on fizzbuzzer.com.
]]>The post Ransom Note Challenge appeared first on fizzbuzzer.com.
]]>Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No
.
For example, the note is “Attack at dawn”. The magazine contains only “attack at dawn”. The magazine has all the right words, but there’s a case mismatch. The answer is No
.
Function Description
Write a function checkMagazine
that prints Yes
if the note can be formed using the magazine, or No
.
checkMagazine
has the following parameters:
* magazine
: an array of strings, each a word in the magazine
* note
: an array of strings, each a word in the ransom note
Solution
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { static Map<String, Integer> createMapWithWordCount(String[] words) { Map<String, Integer> word2Count = new HashMap<String, Integer>(); for (String word:words) { if (word2Count.containsKey(word)) { int count = word2Count.get(word); word2Count.put(word, count+1); } else { word2Count.put(word, 1); } } return word2Count; } // Complete the checkMagazine function below. static void checkMagazine(String[] magazine, String[] note) { Map<String, Integer> magazineWord2Count = createMapWithWordCount(magazine); for (String word:note) { if (magazineWord2Count.containsKey(word) && magazineWord2Count.get(word)>0) { int count = magazineWord2Count.get(word); magazineWord2Count.put(word, count-1); } else { System.out.println("No"); return; } } System.out.println("Yes"); } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { String[] mn = scanner.nextLine().split(" "); int m = Integer.parseInt(mn[0]); int n = Integer.parseInt(mn[1]); String[] magazine = new String[m]; String[] magazineItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < m; i++) { String magazineItem = magazineItems[i]; magazine[i] = magazineItem; } String[] note = new String[n]; String[] noteItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { String noteItem = noteItems[i]; note[i] = noteItem; } checkMagazine(magazine, note); scanner.close(); } }
The post Ransom Note Challenge appeared first on fizzbuzzer.com.
]]>The post Minimum Swaps Challenge appeared first on fizzbuzzer.com.
]]>For example, given the array we perform the following steps:
i arr swap (indices) 0 [7, 1, 3, 2, 4, 5, 6] swap (0,3) 1 [2, 1, 3, 7, 4, 5, 6] swap (0,1) 2 [1, 2, 3, 7, 4, 5, 6] swap (3,4) 3 [1, 2, 3, 4, 7, 5, 6] swap (4,5) 4 [1, 2, 3, 4, 5, 7, 6] swap (5,6) 5 [1, 2, 3, 4, 5, 6, 7]
It took swaps to sort the array.
Function Description
Write a function minimumSwaps
that returns an integer representing the minimum number of swaps to sort the array.
minimumSwaps
must have the following parameter(s):
* arr
: an unordered array of integers
Solution
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { static int indexOfMinimumAfterIndex(int[] arr, int index) { int ans = index; int min = arr[index]; for (int i=index+1; i<arr.length; i++) { if (arr[i] < min) { ans = i; min = arr[i]; } } return ans; } static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } static boolean isSorted(int[] arr, int start) { for (int i=start+1; i<arr.length; i++) { if (arr[i]<arr[i-1]) { return false; } } return true; } // Complete the minimumSwaps function below. static int minimumSwaps(int[] arr) { int count = 0; for (int index=0; index<arr.length; index++) { if (!isSorted(arr, index)){ int indexToSwap = indexOfMinimumAfterIndex(arr, index); if (indexToSwap != index) { swap(arr, index, indexToSwap); count++; } } else { return count; } } return count; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] arr = new int[n]; String[] arrItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arrItem = Integer.parseInt(arrItems[i]); arr[i] = arrItem; } int res = minimumSwaps(arr); bufferedWriter.write(String.valueOf(res)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
The post Minimum Swaps Challenge appeared first on fizzbuzzer.com.
]]>The post Counting Valleys Challenge appeared first on fizzbuzzer.com.
]]>A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given Gary’s sequence of up and down steps during his last hike, find and print the number of valleys he walked through.
For example, if Gary’s path is , he first enters a valley units deep. Then he climbs out an up onto a mountain units high. Finally, he returns to sea level and ends his hike.
Write a function countingValleys
. It must return an integer that denotes the number of valleys Gary traversed. countingValleys
has the following parameter(s):
n
: the number of steps Gary takes
s
: a string describing his path
Solution
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the countingValleys function below. static int countingValleys(int n, String s) { int ans = 0; boolean currentlyInValley = false; boolean currentlyAtSeaLevel = true; int d = 0; int u = 0; for (int i=0; i<n; i++) { char ch = s.charAt(i); if (currentlyAtSeaLevel == true && ch=='U') { currentlyAtSeaLevel = false; u++; } else if (currentlyAtSeaLevel == true && ch=='D') { currentlyAtSeaLevel = false; currentlyInValley = true; d++; } else if (ch == 'U') { u++; } else if (ch == 'D') { d++; } if (currentlyInValley == false && u==d) { currentlyAtSeaLevel = true; u=0; d=0; } else if (currentlyInValley == true && u==d) { currentlyAtSeaLevel = true; currentlyInValley = false; u=0; d=0; ans++; } } return ans; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); String s = scanner.nextLine(); int result = countingValleys(n, s); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
The post Counting Valleys Challenge appeared first on fizzbuzzer.com.
]]>The post Stack with min() operation appeared first on fizzbuzzer.com.
]]>Push, which adds a new element atop the stack,
Pop, which removes the top element of the stack,
Find-Min, which returns (but does not remove) the smallest element of the stack
Full Code
package stacksqueues; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import datastructures.MyStack; /** * How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum * element? Push, pop and min should all operate in O(1) time. * * @author lucas */ public class E2 { protected static class MyStackWithMin extends MyStack { MyStack mins; public MyStackWithMin() { mins = new MyStack(); } public void push(int item) { super.push(item); if (item <= min()) { mins.push(item); } } public Integer pop() { int item = (int) super.pop(); if (item == min()) { mins.pop(); } return item; } /** * Return min element on stack * * @return */ public int min() { if (mins.isEmpty()) { return Integer.MAX_VALUE; } else { return (int)mins.peek(); } } } public static void main(String[] args) { MyStackWithMin stack = new MyStackWithMin(); stack.push(3); stack.push(31); stack.push(13); stack.push(2); stack.push(5); System.out.println(stack.min()); } }
The post Stack with min() operation appeared first on fizzbuzzer.com.
]]>The post Given a matrix in which each row and each column is sorted, write a method to find an element in it. appeared first on fizzbuzzer.com.
]]>Solution
Assumptions:
1. Rows are sorted left to right in ascending order. Columns are sorted top to bottom in ascending order.
2. Matrix is of size .
This algorithm works by elimination. Every move to the left (–col) eliminates all the elements below the current cell in that column. Likewise, every move down eliminates all the elements to the left of the cell in that row.
Code
public class SearchMatrix { public static boolean search(int arr[][], int x) { int n = arr.length; int m = arr[0].length; int c = m - 1; int r = 0; while (r < n && c >= 0) { if (x == arr[r][c]) { return true; } else { if (x < arr[r][c]) { c--; } else { r++; } } } return false; } public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4, 5 }, { 11, 12, 13, 14, 15 }, { 21, 22, 23, 24, 25 }, { 31, 32, 33, 34, 35 }, { 41, 42, 43, 44, 45 } }; System.out.println(search(arr, 35)); } }
The post Given a matrix in which each row and each column is sorted, write a method to find an element in it. appeared first on fizzbuzzer.com.
]]>