Finding unpaired number in an odd Array of integersFind two unique integers in sorted arrayFinding all integers in an array with odd occurrenceRotate an array to the right by a given number of stepsFinding an equilibrium index in an int arrayFind balanced arrayCyclic RotationDetermining the cardinality of sets defined by recursively following indexesGCD of several integersCodility cyclic rotation solution in PHPFind value that occurs in odd number of elements
What is the German equivalent of the proverb 水清ければ魚棲まず (if the water is clear, fish won't live there)?
Complexity of verifying optimality in (mixed) integer programming
If you inherit a Roth 401(k), is it taxed?
Is it safe if the neutral lead is exposed and disconnected?
A variant of the Multiple Traveling Salesman Problem
Why does aggregate initialization not work anymore since C++20 if a constructor is explicitly defaulted or deleted?
What is a good example for artistic ND filter applications?
Why would an invisible personal shield be necessary?
Accidentally deleted everything from a directory on my Macbook using terminal
How to store my pliers and wire cutters on my desk?
Would people understand me speaking German all over Europe?
How to innovate in OR
What is the reason for cards stating "Until end of turn, you don't lose this mana as steps and phases end"?
Can a US President, after impeachment and removal, be re-elected or re-appointed?
Why were contact sensors put on three of the Lunar Module's four legs? Did they ever bend and stick out sideways?
Is it okay for me to decline a project on ethical grounds?
Why does the Eurostar not show youth pricing?
Was the Psych theme song written for the show?
Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?
What are the cons of stateless password generators?
Can Papyrus be folded?
Why was the LRV's speed gauge displaying metric units?
How to efficiently shred a lot of cabbage?
Piece of chess engine, which accomplishes move generation
Finding unpaired number in an odd Array of integers
Find two unique integers in sorted arrayFinding all integers in an array with odd occurrenceRotate an array to the right by a given number of stepsFinding an equilibrium index in an int arrayFind balanced arrayCyclic RotationDetermining the cardinality of sets defined by recursively following indexesGCD of several integersCodility cyclic rotation solution in PHPFind value that occurs in odd number of elements
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
class Solution
public int solution(int[] A)
final int len = A.length;
Arrays.sort(A);
for (int i = 0; i < len ;)
int counter = 1;
int current = A[i];
while ((i < len - 1) && (current == A[++i]))
counter++;
if (counter % 2 == 1)
return current;
return -1;
Could this code be bettered in terms of time complexity of code quality?
java array complexity
$endgroup$
add a comment |
$begingroup$
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
class Solution
public int solution(int[] A)
final int len = A.length;
Arrays.sort(A);
for (int i = 0; i < len ;)
int counter = 1;
int current = A[i];
while ((i < len - 1) && (current == A[++i]))
counter++;
if (counter % 2 == 1)
return current;
return -1;
Could this code be bettered in terms of time complexity of code quality?
java array complexity
$endgroup$
add a comment |
$begingroup$
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
class Solution
public int solution(int[] A)
final int len = A.length;
Arrays.sort(A);
for (int i = 0; i < len ;)
int counter = 1;
int current = A[i];
while ((i < len - 1) && (current == A[++i]))
counter++;
if (counter % 2 == 1)
return current;
return -1;
Could this code be bettered in terms of time complexity of code quality?
java array complexity
$endgroup$
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
class Solution
public int solution(int[] A)
final int len = A.length;
Arrays.sort(A);
for (int i = 0; i < len ;)
int counter = 1;
int current = A[i];
while ((i < len - 1) && (current == A[++i]))
counter++;
if (counter % 2 == 1)
return current;
return -1;
Could this code be bettered in terms of time complexity of code quality?
java array complexity
java array complexity
edited Jul 19 at 20:11
Linny
1,4522 gold badges9 silver badges28 bronze badges
1,4522 gold badges9 silver badges28 bronze badges
asked Jul 19 at 20:06
AnirudhAnirudh
4542 gold badges9 silver badges24 bronze badges
4542 gold badges9 silver badges24 bronze badges
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation
public class Test
public static void main()
int a = 0;
int[] arr = 9,3,9,3,9,7,9;
for (int i = 0; i < arr.length; i++ )
a = a ^ arr[i];
System.out.println(a);
Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.
$endgroup$
1
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
It's possible to use a stream andreduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.
$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
add a comment |
$begingroup$
Regarding time complexity. If you use an additional array, you can make only one passage through the array (not doing sorting) and have time complexity
O(N)
, whereN
- the number of elements in the array. Currently, it'sO(NlogN)
because of sorting.Currently looks like if your method returns -1, it means that you have an even number of elements in the array (Invalid input?) So maybe you should throw some Exception such as
IllegalArgumentException
in this case? Moreover, what if you have elements with value -1 in your array?You should simplify your loops. You have nested loop structure, however, you can have only one since you traverse the array only once. Currently, because of 2 loop structures, it takes some time to understand what's going on, where you increment your
i
variable, what is the stop condition, etc.
Minor comments
- Do not start your variable names with a capital letter (
A
). This convention is reserved for classes.
Edit
Now it came to my mind that you can solve this task with one passage (in O(N)
) without an additional array.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224501%2ffinding-unpaired-number-in-an-odd-array-of-integers%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation
public class Test
public static void main()
int a = 0;
int[] arr = 9,3,9,3,9,7,9;
for (int i = 0; i < arr.length; i++ )
a = a ^ arr[i];
System.out.println(a);
Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.
$endgroup$
1
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
It's possible to use a stream andreduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.
$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
add a comment |
$begingroup$
Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation
public class Test
public static void main()
int a = 0;
int[] arr = 9,3,9,3,9,7,9;
for (int i = 0; i < arr.length; i++ )
a = a ^ arr[i];
System.out.println(a);
Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.
$endgroup$
1
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
It's possible to use a stream andreduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.
$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
add a comment |
$begingroup$
Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation
public class Test
public static void main()
int a = 0;
int[] arr = 9,3,9,3,9,7,9;
for (int i = 0; i < arr.length; i++ )
a = a ^ arr[i];
System.out.println(a);
Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.
$endgroup$
Sorting of the array will take O(n (log n)) in the average case. You can do it in linear time using bitwise operation
public class Test
public static void main()
int a = 0;
int[] arr = 9,3,9,3,9,7,9;
for (int i = 0; i < arr.length; i++ )
a = a ^ arr[i];
System.out.println(a);
Any number which will XOR with 0 will be the number itself. But if it will XOR with itself, it will be 0. In the end, we'll get the non paired number.
answered Jul 20 at 0:59
VikasVikas
461 bronze badge
461 bronze badge
1
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
It's possible to use a stream andreduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.
$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
add a comment |
1
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
It's possible to use a stream andreduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.
$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
1
1
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
Nice. One drawback is that this method will always return a result, even if the array is empty, if it contains no single integer or if it contains multiple unpaired int.
$endgroup$
– Eric Duminil
Jul 20 at 8:13
$begingroup$
It's possible to use a stream and
reduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
It's possible to use a stream and
reduce
for a relatively clean one-liner. As a bonus, it fails with an empty array.$endgroup$
– Eric Duminil
Jul 20 at 8:24
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
@EricDuminil, Here are the requirements from the original question - "A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired". Moreover, we don't need to run the loop if the array is empty. Easy to code a one-line condition.
$endgroup$
– Vikas
Jul 22 at 22:18
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
$begingroup$
sure, the above specs say so. It doesn't hurt to try to make the method more reliable, though.
$endgroup$
– Eric Duminil
Jul 23 at 5:06
add a comment |
$begingroup$
Regarding time complexity. If you use an additional array, you can make only one passage through the array (not doing sorting) and have time complexity
O(N)
, whereN
- the number of elements in the array. Currently, it'sO(NlogN)
because of sorting.Currently looks like if your method returns -1, it means that you have an even number of elements in the array (Invalid input?) So maybe you should throw some Exception such as
IllegalArgumentException
in this case? Moreover, what if you have elements with value -1 in your array?You should simplify your loops. You have nested loop structure, however, you can have only one since you traverse the array only once. Currently, because of 2 loop structures, it takes some time to understand what's going on, where you increment your
i
variable, what is the stop condition, etc.
Minor comments
- Do not start your variable names with a capital letter (
A
). This convention is reserved for classes.
Edit
Now it came to my mind that you can solve this task with one passage (in O(N)
) without an additional array.
$endgroup$
add a comment |
$begingroup$
Regarding time complexity. If you use an additional array, you can make only one passage through the array (not doing sorting) and have time complexity
O(N)
, whereN
- the number of elements in the array. Currently, it'sO(NlogN)
because of sorting.Currently looks like if your method returns -1, it means that you have an even number of elements in the array (Invalid input?) So maybe you should throw some Exception such as
IllegalArgumentException
in this case? Moreover, what if you have elements with value -1 in your array?You should simplify your loops. You have nested loop structure, however, you can have only one since you traverse the array only once. Currently, because of 2 loop structures, it takes some time to understand what's going on, where you increment your
i
variable, what is the stop condition, etc.
Minor comments
- Do not start your variable names with a capital letter (
A
). This convention is reserved for classes.
Edit
Now it came to my mind that you can solve this task with one passage (in O(N)
) without an additional array.
$endgroup$
add a comment |
$begingroup$
Regarding time complexity. If you use an additional array, you can make only one passage through the array (not doing sorting) and have time complexity
O(N)
, whereN
- the number of elements in the array. Currently, it'sO(NlogN)
because of sorting.Currently looks like if your method returns -1, it means that you have an even number of elements in the array (Invalid input?) So maybe you should throw some Exception such as
IllegalArgumentException
in this case? Moreover, what if you have elements with value -1 in your array?You should simplify your loops. You have nested loop structure, however, you can have only one since you traverse the array only once. Currently, because of 2 loop structures, it takes some time to understand what's going on, where you increment your
i
variable, what is the stop condition, etc.
Minor comments
- Do not start your variable names with a capital letter (
A
). This convention is reserved for classes.
Edit
Now it came to my mind that you can solve this task with one passage (in O(N)
) without an additional array.
$endgroup$
Regarding time complexity. If you use an additional array, you can make only one passage through the array (not doing sorting) and have time complexity
O(N)
, whereN
- the number of elements in the array. Currently, it'sO(NlogN)
because of sorting.Currently looks like if your method returns -1, it means that you have an even number of elements in the array (Invalid input?) So maybe you should throw some Exception such as
IllegalArgumentException
in this case? Moreover, what if you have elements with value -1 in your array?You should simplify your loops. You have nested loop structure, however, you can have only one since you traverse the array only once. Currently, because of 2 loop structures, it takes some time to understand what's going on, where you increment your
i
variable, what is the stop condition, etc.
Minor comments
- Do not start your variable names with a capital letter (
A
). This convention is reserved for classes.
Edit
Now it came to my mind that you can solve this task with one passage (in O(N)
) without an additional array.
edited Jul 19 at 23:33
answered Jul 19 at 23:18
Hlib BabiiHlib Babii
1312 bronze badges
1312 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224501%2ffinding-unpaired-number-in-an-odd-array-of-integers%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown