Strings are added to the array, to determine whether the list is ordered by increasing the length of the string. If not, print the index of the first element that violates such ordering.
Everything works correctly if the strings in the array are different, for example, enter
113
13476
Neutral
wa
Answer: index (wa) 3 output.
but if it will be like this:
123
12345
123
Answer: index (123) - 0 but the correct answer is index 2
public class Solution {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add(scan.nextLine());
}
int count = 0;
for(int i = 0; i < list.size(); i++){
if(count+2 > list.size()) {
break;
}
if(list.get(i+1).length() <= list.get(i).length()){
System.out.println(list.indexOf(list.get(i+1)));
break;
}
count = count + 1;
}
}
}
You should change
list.indexOf(list.get(i+1))
to
i+1
since if there are multiple occurrences of the same String in the List, you want to return the index of the first element that violates the ordering, which is i+1 (and not the index of the first String which is equal to that element).
BTW, even if there were no duplicate elements in your List, it would no sense to use list.indexOf(list.get(i+1)) instead of simply i+1.
You don't need to use lastIndexOf - you already have the index:
// Stsrt at index 1, as index 0 can never violate the rule:
for (int i = 1; i < list.size(); i++) {
if (list.get(i).length() < list.get(i - 1).length() {
System.out.println("Rule violated at index " + i + " (" + list.get(i) + ")");
break;
}
}
You could also use PriorityQueue and check within the supplied Comparator
PriorityQueue<String> p = new PriorityQueue<>((a, b) -> {
if (a.length() > b.length()) {
throw new RuntimeException(a);
}
return 0;
});
p.add("foo");
try {
p.add("bar2");
} catch (RuntimeException e) {
System.out.println(p.size());
}
}
Related
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:
public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {
int numLength1 = src1.array.length;
int numLength2 = src2.array.length;
//combined array lengths
int myLength = (numLength1 + numLength2);
// System.out.println(myLength);
OrderedArray mergedArr = new OrderedArray(myLength);
//new array
long[] merged = new long[myLength];
//loop to sort array
int i = 0;
int j = 0;
int k = 0;
while (k < src1.array.length + src2.array.length - 1) {
if(src1.array[i] < src2.array[j]) {
merged[k] = src1.array[i];
i++;
}
else {
merged[k] = src2.array[j];
j++;
}
k++;
}
//loop to print result
for(int x = 0; x < myLength; x++) {
System.out.println(merged[x]);
}
return mergedArr;
}
public static void main(String[] args) {
int maxSize = 100; // array size
// OrderedArray arr; // reference to array
OrderedArray src1 = new OrderedArray(4);
OrderedArray src2 = new OrderedArray(5);
// arr = new OrderedArray(maxSize); // create the array
src1.insert(1); //insert src1
src1.insert(17);
src1.insert(42);
src1.insert(55);
src2.insert(8); //insert src2
src2.insert(13);
src2.insert(21);
src2.insert(32);
src2.insert(69);
OrderedArray myArray = merge(src1, src2);
This is my expected output:
1
8
13
17
21
32
42
55
69
and this is my current output:
1
8
13
17
21
32
42
55
0
While merging two arrays you are comparing them, sorting and merging but what if the length of two arrays is different like Array1{1,3,8} and Array2{4,5,9,10,11}. Here we will compare both arrays and move the pointer ahead, but when the pointer comes at 8 in array1 and at 9 in array2, now we cannot compare ahead, so we will add the remaining sorted array;
Solution:-
(Add this code between loop to sort array and loop to print array)
while (i < numLength1) {
merged[k] = src1.array[i];
i++;
k++;
}
while (j < numLength2) {
merged[k] = src2.array[j];
j++;
k++;
}
To answer your main question, the length of your target array is src1.array.length + src2.array.length, so your loop condition should be one of:
while (k < src1.array.length + src2.array.length) {
while (k <= src1.array.length + src2.array.length - 1) {
Otherwise, you will never set a value for the last element, where k == src1.array.length + src2.array.length - 1.
But depending on how comprehensively you test the code, you may then find you have a bigger problem: ArrayIndexOutOfBoundsException. Before trying to use any array index, such as src1.array[i], you need to be sure it is valid. This condition:
if(src1.array[i] < src2.array[j]) {
does not verify that i is a valid index of src1.array or that j is a valid index of src2.array. When one array has been fully consumed, checking this condition will cause your program to fail. You can see this with input arrays like { 1, 2 } & { 1 }.
This revision of the code does the proper bounds checks:
if (i >= src1.array.length) {
// src1 is fully consumed
merged[k] = src2.array[j];
j++;
} else if (j >= src2.array.length || src1.array[i] < src2.array[j]) {
// src2 is fully consumed OR src1's next is less than src2's next
merged[k] = src1.array[i];
i++;
} else {
merged[k] = src2.array[j];
j++;
}
Note that we do not need to check j in the first condition because i >= src1.array.length implies that j is a safe value, due to your loop's condition and the math of how you are incrementing those variables:
k == i + j due to parity between k's incrementing and i & j's mutually exclusive incrementing
k < src1.array.length + src2.array.length due to the loop condition
Therefore i + j < src1.array.length + src2.array.length
If both i >= src1.array.length and j >= src2.array.length then i + j >= src1.array.length + src2.array.length, violating the facts above.
A couple other points and things to think about:
Be consistent with how you refer to data. If you have variables, use them. Either use numLength1 & numLength2 or use src1.length & src2.length. Either use myLength or use src1.array.length + src2.array.length.
Should a merge method really output its own results, or should the code that called the method (main) handle all the input & output?
Is the OrderedArray class safe to trust as "ordered", and is it doing its job properly, if you can directly access its internal data like src1.array and make modifications to the array?
The best way to merge two arrays without repetitive items in sorted order is that insert both of them into treeSet just like the following:
public static int[] merge(int[] src1, int[] src2) {
TreeSet<Integer> mergedArray= new TreeSet<>();
for (int i = 0; i < src1.length; i++) {
mergedArray.add(src1[i]);
}
for (int i = 0; i < src2.length; i++) {
mergedArray.add(src2[i]);
}
return mergedArray.stream().mapToInt(e->(int)e).toArray();
}
public static void main(String[] argh) {
int[] src1 = {1,17,42,55};
int[] src2 = {8,13,21,32,69};
Arrays.stream(merge(src1,src2)).forEach(s-> System.out.println(s));
}
output:
1
8
13
17
21
32
42
55
69
I'm trying to solve the problem below from CodeFights. I left my answer in Java after the question. The code works for all the problems, except the last one. Time limit exception is reported. What could I do to make it run below 3000ms (CodeFights requirement)?
Note: Write a solution with O(n) time complexity and O(1) additional space complexity, since this is what you would be asked to do during a real interview.
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.
Example
For a = [2, 3, 3, 1, 5, 2], the output should be
firstDuplicate(a) = 3.
There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than than second occurrence of 2 does, so the answer is 3.
For a = [2, 4, 3, 5, 1], the output should be
firstDuplicate(a) = -1.
Input/Output
[time limit] 3000ms (java)
[input] array.integer a
Guaranteed constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
[output] integer
The element in a that occurs in the array more than once and has the minimal index for its second occurrence. If there are no such elements, return -1.
int storedLeastValue = -1;
int indexDistances = Integer.MAX_VALUE;
int indexPosition = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++)
{
int tempValue = a[i];
for (int j = i+1; j < a.length; j++) {
if(tempValue == a[j])
{
if(Math.abs(i-j) < indexDistances &&
j < indexPosition)
{
storedLeastValue = tempValue;
indexDistances = Math.abs(i-j);
indexPosition = j;
break;
}
}
}
}
return storedLeastValue;
Your solution has two nested for loops which implies O(n^2) while the question explicitly asks for O(n). Since you also have a space restriction you can't use an additional Set (which can provide a simple solution as well).
This question is good for people that have strong algorithms/graph theory background. The solution is sophisticated and includes finding an entry point for a cycle in a directed graph. If you're not familiar with these terms I'd recommend that you'll leave it and move to other questions.
Check this one, it's also O(n) , but without additional array.
int firstDuplicate(int[] a) {
if (a.length <= 1) return -1;
for (int i = 0; i < a.length; i++) {
int pos = Math.abs(a[i]) - 1;
if (a[pos] < 0) return pos + 1;
else a[pos] = -a[pos];
}
return -1;
}
The accepted answer does not work with the task.
It would work if the input array would indeed contain no bigger value than its length.
But it does, eg.: [5,5].
So, we have to define which number is the biggest.
int firstDuplicate(int[] a) {
int size = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] > size) {
size = a[i];
}
}
int[] t = new int[size+1];
for(int i = 0; i < a.length; i++) {
if(t[a[i]] == 0) {
t[a[i]]++;
} else {
return a[i];
}
}
return -1;
}
What about this:
public static void main(String args[]) {
int [] a = new int[] {2, 3, 3, 1, 5, 2};
// Each element of cntarray will hold the number of occurrences of each potential number in the input (cntarray[n] = occurrences of n)
// Default initialization to zero's
int [] cntarray = new int[a.length + 1]; // need +1 in order to prevent index out of bounds errors, cntarray[0] is just an empty element
int min = -1;
for (int i=0;i < a.length ;i++) {
if (cntarray[a[i]] == 0) {
cntarray[a[i]]++;
} else {
min = a[i];
// no need to go further
break;
}
}
System.out.println(min);
}
You can store array values in hashSet. Check if value is already present in hashSet if not present then add it in hashSet else that will be your answer. Below is code which passes all test cases:-
int firstDuplicate(int[] a) {
HashSet<Integer> hashSet = new HashSet<>();
for(int i=0; i<a.length;i++){
if (! hashSet.contains(a[i])) {
hashSet.add(a[i]);
} else {
return a[i];
}
}
return -1;
}
My simple solution with a HashMap
int solution(int[] a) {
HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();
int min = -1;
for (int i=0; i < a.length; i++) {
if (!(countMap.containsKey(a[i]))) {
countMap.put(a[i],1);
}
else {
return a[i];
}
}
return min;
}
Solution is very simple:
Create a hashset
keep iterating over the array
if element is already not in the set, add it.
else element will be in the set, then it mean this is minimal index of first/second the duplicate
int solution(int[] a) {
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<a.length; i++){
if(set.contains(a[i])){
// as soon as minimal index duplicate found where first one was already in the set, return it
return a[i];
}
set.add(a[i]);
}
return -1;
}
A good answer for this exercise can be found here - https://forum.thecoders.org/t/an-interesting-coding-problem-in-codefights/163 - Everything is done in-place, and it has O(1) solution.
I am supposed to create a method that will merge two given pre-sorted ArrayLists of Strings into one. All of it has to be done in one loop. The way I have gone about it is comparing the two ArrayLists at each index and adding them in alphabetical order based on those comparisons. The problem with this is that if you are given two ArrayLists ["Bob", "Jill"] and ["Watson", "Zane"], the output would be ["Bob", "Watson", "Jill", "Zane"]. This is clearly not sorted.
That being said, I know what the problem is, I just don't know how to implement a fix for it.
Code:
public static ArrayList<String> merge(ArrayList<String> al1, ArrayList<String> al2){
ArrayList<String> al = new ArrayList<String> (al1.size() + al2.size());
for (int i = 0; i < Math.max(al1.size(), al2.size()); i++) { // Loops until max size of the two arraylists is reached
if (i < al1.size() && i < al2.size()) { // Checks if the index is still in range of both arraylists
if (al1.get(i).compareTo(al2.get(i)) < 0) { // Compares the two arraylists at the same index
al.add(al1.get(i));
al.add(al2.get(i));
} else {
al.add(al2.get(i));
al.add(al1.get(i));
}
} else if (i < al1.size() && i > al2.size()) { // Checks if the index is greater than the size of al2
al.add(al1.get(i));
} else { // Anything else, just add al2
al.add(al2.get(i));
}
}
return al;
public static ArrayList<Double> merge(ArrayList<Double> a, ArrayList<Double> b) {
ArrayList<Double> toReturn = new ArrayList<Double>();
int a_ = 0;
int b_ = 0;
for(int j = 0; j < a.size() + b.size(); j++) {
if(a_ == a.size())
toReturn.add(b.get(b_++));
else if(b_ == b.size())
toReturn.add(a.get(a_++));
else if(a.get(a_).compareTo(b.get(b_)) < 0)
toReturn.add(a.get(a_++));
else
toReturn.add(b.get(b_++));
}
return toReturn;
}
You're using one index, i, to index into both a1 and a2, which means that you can't move through the two lists independently. As you've noticed, a pair of lists like [1, 2, 3] and [4, 5, 6] should be merged by taking all three elements from the first list and then taking the elements from the second list. By traversing both lists simultaneously as you're doing that's not possible.
Instead track two separate indicies, say i1 and i2, and increment them independently. At each iteration determine which index is smaller, add that value and increment that index. Once you've reached the end of one list or the other you just drain the remaining list.
You shoud take a look at merge step of merge-sort algo:
https://en.wikipedia.org/wiki/Merge_sort
All in all you should have something like:
int i = 0;
int j = 0;
while (i < a.size() && j < b.size()) {
if (a.get(i).compareTo(b.get(j)) <= 0) {
result.add(a.get(i));
++i;
} else {
result.add(b.get(j));
++j;
}
}
for (; i < a.size(); ++i) {
result.add(a.get(i));
}
for (; j < a.size(); ++j) {
result.add(b.get(j));
}
return result;
Didin't test it, however in result you should have something that looks the same
This question already has answers here:
How to efficiently remove duplicates from an array without using Set
(48 answers)
Closed 8 years ago.
I have written a method to count the number of occurrences of the words in a word file. Prior, in another method, i have sorted the words to appear in alphabetical order. There for a sample input into this method will look like this:
are
away
birds
birds
going
going
has
My question is.. How do i delete the repeated occurrences in this method? (after counting ofcoz) I have tried to use another string array to copy the unique ones into that string array, but i get a null pointer exception.
public static String[] counter(String[] wordList)
{
for (int i = 0; i < wordList.length; i++)
{
int count = 1;
for(int j = 0; j < wordList.length; j++)
{
if(i != j) //to avoid comparing itself
{
if (wordList[i].compareTo(wordList[j]) == 0)
{
count++;
}
}
}
System.out.println (wordList[i] + " " + count);
}
return wordList;
}
Any help will be much appreciated.
Oh, and my current output looks something like this:
are 1
away 1
birds 2
birds 2
going 2
going 2
has 1
I would prefer using Map to store word occurrence. Keys in the map are stored in Set so it can't be duplicated. What about something like this?
public static String[] counter(String[] wordList) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i];
if (map.keySet().contains(word)) {
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
}
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
return wordList;
}
I already posted an answer on this question. Your question is almost identical - he was having problems creating another array and getting an NPE too.
This is what I came up with (assuming the array is sorted):
public static String[] noDups(String[] myArray) {
int dups = 0; // represents number of duplicate numbers
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is the same
if (myArray[i].equals(myArray[i - 1]))
dups++; // add one to number of duplicates
}
// create return array (with no duplicates)
// and subtract the number of duplicates from the original size (no NPEs)
String[] returnArray = new String[myArray.length - dups];
returnArray[0] = myArray[0]; // set the first positions equal to each other
// because it's not iterated over in the loop
int count = 1; // element count for the return array
for (int i = 1; i < myArray.length; i++)
{
// if current number in original array is not the same as the one before
if (!myArray[i].equals(myArray[i-1]))
{
returnArray[count] = myArray[i]; // add the number to the return array
count++; // continue to next element in the return array
}
}
return returnArray; // return the ordered, unique array
}
Sample input/output:
String[] array = {"are", "away", "birds", "birds", "going", "going", "has"};
array = noDups(array);
// print the array out
for (String s : array) {
System.out.println(s);
}
Outputs:
are
away
birds
going
has
I am trying to solve this, but i don't know how...
Values[10] = {1,1,4,4,2,3,3,2,1,3}
to print:
{1,2,3,4} or {1,4,2,3} (not sorted, any order, but distinct)
I also need to count the number of times each number has occurred, both without sort, new arrays or boolean methods or other data structures, please advise as i am stuck.
Is there a simple method i can use to just print the unique values/ distinct values ?
It can be accomplished if your are willing to destroy your current array. and you assume that the array is either of type Integer (so nullable) or if not there is some bound such as all int are poistive so you can use -1.
for(int i = 0; i < values.length; i++){ //for entire array
Integer currVal = values[i]; // select current value
int count = 1; // and set count to 1
if(currVal != null){ // if value not seen
for( int j = i + 1; j < values.length; j++){ // for rest of array
if(values[j] == currVal){ // if same as current Value
values[j] = null; // mark as seen
count++; // and count it
}
}
System.out.print("Number : " + currVal + " Count : " + count + "\n");
//print information
}
// if seen skip.
}
In plain english, Go through the array in 2 loops, roughly O(n^2) time.
Go to index i. If index has not yet been seen (is not null) then go through the rest of array, mark any indexs with same value as seen (make it null) and increment count varable. At end of loop print value and count. If Index has be seen (is null) skip and go to next index. At end of both loops all values will be left null.
Input : Values[] = {1,1,4,4,2,3,3,2,1,3}
Output : Values[] = {1,null,4,null,2,3,null,null,null,null}
Number : 1 Count : 3
Number : 4 Count : 2
Number : 2 Count : 2
Number : 3 Count : 3
Edit: corrected my mistake in output, pointed out by commenters.
Another solution, without creating additional objects:
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
if (i == 0 || value[i] != value[i-1]) {
System.out.println(values[i]);
}
}
And the shortest solution I can think of:
Integer[] values = {1,1,4,4,2,3,3,2,1,3};
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(values));
System.out.println(set);
Assuming the values are guaranteed to be integers, you could also do it by incrementing a check value, scan over the array, sum the number of that check value in the array, add it to an accumulator and loop while the accumulator < array.length.
Something like this (untested):
public void checkArray(int[] toCheck) {
int currentNum = 0;
int currentCount = 0;
int totalSeen = 0;
StringBuilder sb = new StringBuilder();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0; i<toCheck.length; i++) {
min = Math.min(toCheck[i], min);
max = Math.max(toCheck[i], max);
}
System.out.print("{ ");
for(currentNum = min; currentNum < max; currentNum++) {
for(int i=0; i<toCheck.length; i++) {
if(toCheck[i] == currentNum) currentCount++;
}
if(currentCount != 0) {
if(currentNum == min) System.out.print(currentCount + "(" +currentCount+ ")");
else System.out.print(", " + currentCount + " (" +currentCount+ ")");
}
totalSeen += currentCount;
currentCount = 0;
}
System.out.println(" }");
}
It should be noted that while this technically fulfills all your requirements, it will be far less efficient than gbtimmon's approach.
If your ints were {1,2,3,150000}, for example, it will needlessly spin over all the values between 4 and 149999.
Edit: added better limits from tbitof's suggestion.
Your question isn't quite clear to me, since it sounds like you want to do these things without creating any additional objects at all. But if it's just about not creating another array, you could use a Map<Integer, Integer>, where the key is the number from your original array, and the value is the count of times you've seen it. Then at the end you can look up the count for all numbers, and print out all the keys by using Map.keyset()
Edit: For example:
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for( int i : values ) {
if( counts.containsKey(i) ) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
// get the set of unique keys
Set uniqueInts = counts.keyset();