Medium
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a and b, check whether they are similar.
Example
-
For a = [1, 2, 3] and b = [1, 2, 3], the output should be
areSimilar(a, b) = true.The arrays are equal, no need to swap any elements.
-
For a = [1, 2, 3] and b = [2, 1, 3], the output should be
areSimilar(a, b) = true.We can obtain b from a by swapping 2 and 1 in b.
-
For a = [1, 2, 2] and b = [2, 1, 1], the output should be
areSimilar(a, b) = false.Any swap of any two elements either in a or in b won't make a and b equal.
Input/Output
-
[execution time limit] 0.5 seconds (c)
-
[input] array.integer a
Array of integers.
Guaranteed constraints:
3 ≤ a.length ≤ 10^5,
1 ≤ a[i] ≤ 1000. -
[input] array.integer b
Array of integers of the same length as a.
Guaranteed constraints:
b.length = a.length,
1 ≤ b[i] ≤ 1000. -
[output] boolean
- true if a and b are similar, false otherwise.
[C] Syntax Tips
// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
char * answer = malloc(strlen(name) + 8);
printf("This prints to the console when you Run Tests");
strcpy(answer, "Hello, ");
strcat(answer, name);
return answer;
}
Solution 1
// Arrays are already defined with this interface:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
bool areSimilar(arr_integer a,arr_integer b)
{
int index;
bool isSame=true;
for(int i=0;i<a.size;i++)
if(a.arr[i]!=b.arr[i])
{
isSame=false;
index=i;
break;
}
if(isSame)
return true;
for(int i=index+1;i<a.size;i++)
if(a.arr[i]!=b.arr[i])
{
int temp=a.arr[i];
a.arr[i]=a.arr[index];
a.arr[index]=temp;
break;
}
for(int i=0;i<a.size;i++)
if(a.arr[i]!=b.arr[i])
return false;
return true;
}
Solution 2
// Arrays are already defined with this interface:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
bool areSimilar(arr_integer a,arr_integer b)
{
bool different=false;
for(int i=0;i<a.size;i++)
if(a.arr[i]!=b.arr[i])
{
int j=i+1, temp;
if(different)
return false;
different=true;
while(b.arr[j]!=a.arr[i] || b.arr[i]!=a.arr[j])
{
j++;
if(j>=b.size)
return false;
}
temp=b.arr[i];
b.arr[i]=b.arr[j];
b.arr[j]=temp;
}
return true;
}
'Codesignal' 카테고리의 다른 글
<Codesignal> palindromeRearranging (0) | 2020.04.05 |
---|---|
<Codesignal> arrayChange (0) | 2020.04.05 |
<Codesignal> Add Border (0) | 2020.04.05 |
<Codesignal> alternatingSums (0) | 2020.04.05 |
<Codesignal> reverseInParentheses (0) | 2020.04.05 |