Array with duplicates [4,4,1]. Find pairs with sum 5 in O(n).
Expected output (4,1) and (4,1) and count is 2.
Approach#1:
Using HashSet:
public static int twoSum(int[] numbers, int target) {
HashSet<Integer> set = new HashSet<Integer>();
int c = 0;
for(int i:numbers){
if(set.contains(target-i)){
System.out.println(i+"-"+(target-i));
c++;
}
set.add(i);
}
return c;
}
Output is 1.
Approach #2 as stated in this link:
private static final int MAX = 100000;
static int printpairs(int arr[],int sum)
{
int count = 0;
boolean[] binmap = new boolean[MAX];
for (int i=0; i<arr.length; ++i)
{
int temp = sum-arr[i];
if (temp>=0 && binmap[temp])
{
count ++;
}
binmap[arr[i]] = true;
}
return count;
}
Output 1.
However the O(nlog n) solution is using sorting the array:
public static int findPairs(int [] a, int sum){
Arrays.sort(a);
int l = 0;
int r = a.length -1;
int count = 0;
while(l<r){
if((a[l] + a[r]) == sum){
count ++;
System.out.println(a[l] + " "+ a[r]);
r--;
}
else if((a[l] + a[r])>sum ){
r--;
}else{
l++;
}
}
return count;
}
Can we get the solution in O(n)?
You can use your second approach - just change boolean to int:
public static void main(String[] args) {
System.out.println(printPairs(new int[]{3, 3, 3, 3}, 6)); // 6
System.out.println(printPairs(new int[]{4, 4, 1}, 5)); // 2
System.out.println(printPairs(new int[]{1, 2, 3, 4, 5, 6}, 7)); // 3
System.out.println(printPairs(new int[]{3, 3, 3, 3, 1, 1, 5, 5}, 6)); // 10
}
public static int printPairs(int arr[], int sum) {
int count = 0;
int[] quantity = new int[sum];
for (int i = 0; i < arr.length; ++i) {
int supplement = sum - arr[i];
if (supplement >= 0) {
count += quantity[supplement];
}
quantity[arr[i]]++; // You may need to check that arr[i] is in bounds
}
return count;
}
you can try this also
Map<Integer, List> map = new HashMap<>();
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(k - arr[i])) {
count += map.get(k - arr[i]).size();
}
List<Integer> test = map.getOrDefault(arr[i], new ArrayList<>());
test.add(i);
map.put(arr[i], test);
}
return count;
Here is an O(N) Time & Space approach using HashMap.
class Solution
{
static int getPairsCount(int[] arr, int n, int target)
{
HashMap<Integer,Integer> map = new HashMap<>();
int pairs=0;
for (int i=0; i<n; i++)
{
if (map.containsKey(target - arr[i]))
{
pairs += map.get(target - arr[i]);
for (int j=1; j<=map.get(target - arr[i]); j++)
System.out.print("(" +(target-arr[i])+ "," +arr[i]+ ") ");
}
map.put(arr[i] , map.getOrDefault(arr[i],0)+1);
}
return pairs;
}
public static void main (String [] args)
{
int target = 5;
int [] input = {4, 4, 1};
System.out.println(getPairsCount(input , input.length , target));
target = 10;
input = new int [] {1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1};
System.out.println(getPairsCount(input , input.length , target));
}
}
Output:
2 (Pairs)
(4,1) (4,1)
13 (Pairs)
(5,5) (3,7) (2,8) (6,4) (2,8) (8,2) (8,2) (5,5) (5,5) (1,9) (1,9) (9,1) (9,1)
Related
I am learning Java and wanted to find the contiguous sub-array with maximum sum. I am able to find it, but when I am going outside the for loop, the value of the sub-array saved in an ArrayList changes.
public class FindingSumOfContiguousSubArray {
//code for computing sum of an array list
public int getSum (ArrayList <Integer> arraylist ) {
int sum = 0;
for (int i=0; i<arraylist.size(); i++) {
sum += arraylist.get(i);
}
return sum;
}
private ArrayList<Integer> contigiousSubArray(int [] array){
ArrayList <Integer> finalList = new ArrayList<Integer>();
int n = array.length;
int minVal = -1000;
for(int i = 0; i<n; i++) {
ArrayList<Integer> aList = new ArrayList<Integer>(); //taking local object of ArrayList
for(int j = i; j<n; j++) {
aList.add(array[j]); //{-2, 1}
int sum = getSum(aList);
//System.out.println(minVal);
if (sum > minVal) {
minVal = sum;
//finalList.clear();
finalList = aList;
System.out.println(sum);
System.out.println(finalList);
}
else continue;
}
}
System.out.println(finalList);
return finalList;
}
public static void main(String[] args) {
FindingSumOfContiguousSubArray cSA = new FindingSumOfContiguousSubArray(); //creating class object
int [] inpArray = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
ArrayList <Integer> contFinalList = cSA.contigiousSubArray(inpArray);
//System.out.println(contFinalList);
//System.out.println(cSA.getSum(contFinalList));
}
}
This code gives output:
[1, -3, 4, -1, 2, 1]
5
[4, -1, 2]
6
[4, -1, 2, 1]
[4, -1, 2, 1, -5, 4]
I am not sure why my arraylist is showing [4, -1, 2, 1, -5, 4] outside the for loop.
I'm not exactly sure what you're looking for here, but maybe try this (you don't need your summing method this way):
private static List<Integer> contigiousSubArray(int [] array){
List<Integer> finalList = new ArrayList<>();
int minVal = Integer.MIN_VALUE;
for(int i = 0; i < array.length; i++) {
List<Integer> aList = new ArrayList<Integer>(); //taking local object of ArrayList
for(int j = i; j < array.length; j++) {
aList.add(array[j]); //{-2, 1}
int sum = aList.stream()
.collect(Collectors.summingInt(Integer::intValue));
//System.out.println(minVal);
if (sum > minVal) {
minVal = sum;
finalList.clear();
finalList.addAll(aList);
}
}
}
return finalList;
}
try this :
public int contigiousSubArray(int[] arr) {
int[] result = new int[arr.length];
result[0]=arr[0];
for (int i = 1; i < arr.length; i++) {
result[i]=Math.max(result[i-1]+arr[i], arr[i]);
}
int maxSumArray = result[0];
for (int j = 1; j if(maxSumArray<result[j])
maxSumArray = result[j];
}
return maxSumArray;
}```
This code is about algorithms and datastructures. This code runs perfectly and i just have some questions on it because it seems like i don't understand two points. So my questions for that is:
which informations are in the countingArray?
how often is the while loop executed?
public class CountingSort {
public static void main(String[] args) {
int[] m1 = { 1, 17, 3, 1, 4, 9, 4, 4 };
System.out.println("unsorted:");
output(m1);
int min1 = rangeMin(m1);
int max1 = rangeMax(m1);
countingSort(m1, min1, max1);
System.out.println("sorted:");
output(m1);
int[] m2 = { -1, 13, 3, -1, -4, 9, -4, 4 };
System.out.println("unsorted:");
output(m2);
int min2 = rangeMin(m2);
int max2 = rangeMax(m2);
countingSort(m2, min2, max2);
System.out.println("sorted:");
output(m2);
}
public static void output(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ", ");
}
System.out.println();
}
public static int rangeMin(int[] a) {
int minimum = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < minimum)
minimum = a[i];
}
return minimum;
}
public static int rangeMax(int[] array) {
int maximum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maximum)
maximum = array[i];
}
return maximum;
}
public static void countingSort(int[] array, int rangeMin, int rangeMax) {
int[] countingArray = new int[rangeMax - rangeMin + 1];
for (int i : array) {
countingArray[i - rangeMin]++;
}
int c = 0;
for (int i = rangeMin; i <= rangeMax; i++) {
while (countingArray[i - rangeMin] > 0) {
array[c] = i;
c++;
countingArray[i - rangeMin]--;
}
}
}
}
CountingSort has O(n) time and space complexity. You iterate (i.e. use for loop) twice.
public class CountingSort {
public static void main(String... args) {
proceed(1, 17, 3, 1, 4, 9, 4, 4);
System.out.println("---");
proceed(-1, 13, 3, -1, -4, 9, -4, 4);
}
public static void proceed(int... arr) {
System.out.print("unsorted: ");
print(arr);
countingSort(arr);
System.out.print("sorted: ");
print(arr);
}
public static void print(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(i -> String.format("%2d", i))
.collect(Collectors.joining(",")));
}
public static void countingSort(int... arr) {
int min = Arrays.stream(arr).min().orElse(0);
int max = Arrays.stream(arr).max().orElse(0);
// contains amount of number in the unsorted array
// count[0] - amount of min numbers
// count[count.length - 1] - amount of max numbers
int[] count = new int[max - min + 1];
for (int i : arr)
count[i - min]++;
// fill source array with amount of numbers
for (int i = 0, j = 0; i < count.length; i++)
for (int k = 0; k < count[i]; k++, j++)
arr[j] = min + i;
}
}
I have the following input
int combinationCount = 3;
int arr[] = {1, 1, 2, 2, 3};
combinationCount is {1,2,3}, combinationCount defines the number of sequence of number. For Eg: combinationCount = 3 means {1,2,3} and combinationCount = 2 means {1,2}
Array is always sorted, I want to print the output as the number of combinations as follow
[1,2,3], [1,2,3], [1,2,3], [1,2,3] //I have to iterate the whole array as it is just logic for a problem
Output Explanation (I want to print values, not index):
This is just an explanation of output which shows the index position of the value printed.
Index position of each value
[0, 2, 4], [0, 3, 4], [1, 2, 4], [1, 3, 4]
Example 2
int combinationCount = 2; // means combination is {1,2}
int arr[] = {1, 2, 2};
Print: [1,2], [1,2]
Example 3
int combinationCount = 3; // means combination is {1,2,3}
int arr[] = {1, 1, 3};
Print nothing
The program which I written is as follow:
int combinationCount = 3;
int arr[] = {1, 1, 2, 2, 3};
List<Integer> list = new ArrayList<>();
int prev = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 1) {
prev = 1;
list = new ArrayList<>();
list.add(1);
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] == prev + 1) {
prev = arr[j];
list.add(arr[j]);
} else if (arr[j] > (prev + 1)) {
break;
}
}
if (list.size() == combinationCount) {
System.out.print(list + ",");
}
} else {
break;
}
}
Output coming as
[1,2,3],[1,2,3]
which is not correct
Somewhere I am missing loop and how optimized code we can write? Any suggestions pls. Kindly let me know for any concern.
You can use Cartesian Product. I have used this answer as reference.
public class Test {
public static List<List<Integer>> product(List<List<Integer>> lists) {
List<List<Integer>> result = new ArrayList<>();
int solutions = lists.stream().mapToInt(List::size).reduce(1, (a, b) -> a * b);
for (int i = 0; i < solutions; i++) {
int j = 1;
List<Integer> tempList = new ArrayList<>();
for (List list : lists) {
tempList.add((Integer) list.get((i / j) % list.size()));
j *= list.size();
}
result.add(tempList);
}
return result;
}
public static void main(String[] args) {
int combinationCount = 2, count = 0;
int arr[] = {1, 1, 3};
Map<Integer, List<Integer>> map = new HashMap<>();
List<List<Integer>> combinations = new ArrayList<>();
for (Integer idx = 0; idx < arr.length; idx++) {
map.computeIfAbsent(arr[idx], k -> new ArrayList<>()).add(idx);
}
for (int i = 1; i <= combinationCount; i++) {
if (map.getOrDefault(i, null) != null)
count += 1;
}
if (count == combinationCount) {
List result = product(new ArrayList(map.values()));
System.out.println(result);
} else {
System.out.println("No combination found");
}
}
}
Output:
No combination found
This post - "Java + Count duplicates from int array without using any Collection or another intermediate Array", was also a sample exercise in my book at school, but what I want to do is get the elements that has duplicates without sorting it.
What I did is I removed the duplicates of arrays first, to get only the unique elements and then I compare it to the original array and count how many times the element has been found. But the problem is it doesn't print the correct elements which has duplicates.
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
the correct output should be: 7, 1, 4
but instead it outputs: 7, 6, 1
This is my codes:
//method for removing duplicates
public static int[] removeDuplicates(int[] n) {
int limit = n.length;
for(int i = 0; i < limit; i++) {
for(int j = i + 1; j < limit; j++) {
if(n[i] == n[j]) {
for(int k = j; k < limit - 1; k++) {
n[k] = n[k + 1];
}
limit--;
j--;
}
}
}
int[] uniqueValues = new int[limit];
for(int i = 0; i < uniqueValues.length; i++) {
uniqueValues[i] = n[i];
}
return uniqueValues;
}
//method for getting elements that has duplicates
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
int count = 0;
int limit = u.length;
for(int i = 0; i < u.length; i++) {
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
//main
public static void main(String[] args) {
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
//printing original values
System.out.print(Arrays.toString(num));
System.out.println();
int[] a = getDuplicatedElements(num);
System.out.print("Elements with Duplicates: " + Arrays.toString(a));
}
What's the error in my codes here? Please help thanks...
You have two issues:
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
System.out.println ("unique " + Arrays.toString (u));
int count = 0;
int limit = u.length;
for(int i = 0; i < limit; i++) { // you must use limit instead of u.length
// in order for the loop to terminate
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
i--; // you must decrement i after you find a unique element in u
// otherwise you'll be skipping elements in the u array
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
With those fixes, you'll get the expected output:
Elements with Duplicates: [7, 1, 4]
It's fairly simple when using a stream
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
List<Integer> list = Arrays.stream(num).boxed().collect(Collectors.toList());
list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet()).forEach(System.out::println);
public class arsum
{
static int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
public int[] summing(int[][] array)
{
int index = 0;
int a[] = new int[array[index].length];
for (int i = 0; i < array[0].length; i++)
{
int sum = 0;
for (int j = 0; j < array.length; j++)
{
sum += array[j][i];
}
a[index] = sum;
System.out.println(sum);
}
return a;
}
public static void main(String[] args) {
new arsum().summing(myarray);
}
}
At the moment it prints out all 4 column sums, however I only want the last sum. I cannot figure out how to code it properly for any general array.
I am new to coding and have not totally figured everything out yet.
Try,
int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
int sum = 0;
for (int nums[] : myarray) {
sum += nums[nums.length - 1];
}
System.out.println(sum);
you can also use array indexing to print sum of last column as below:-
public static int summing(int[][] array)
{
int row = array.length;
int sum = 0;
for (int i = row - 1; i > row - 2; i--) {
int col = myarray[i].length;
for (int j = 0; j < col; j++) {
sum += array[i][j];
}
System.out.println(sum);
}
return sum;
}