
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make Both Arrays Equal by Modifying a Single Element in Python
Suppose we have two arrays nums1 and nums2 and another value k. We have to check whether both arrays can be made equal by modifying any one element from the nums1 in the following way (only once): We can add any value from the range [-k, k] to any element of nums1.
So, if the input is like nums1 = [5,7,11] nums2 = [5,5,11] k = 8, then the output will be True as we can add -2 (in range [-8,8]) with nums1[1] to make it 5 then it will be same as nums2.
To solve this, we will follow these steps −
- sort the list nums1 and nums2
- temp := False
- idx := -1
- for i in range 0 to size of nums1 - 1, do
- if nums1[i] is not same as nums2[i], then
- if temp is true, then
- return False
- temp := True
- idx := i
- if temp is true, then
- if nums1[i] is not same as nums2[i], then
- if idx is -1 or |nums1[idx]-nums2[idx]| <= k, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(nums1, nums2, k): nums1.sort() nums2.sort() temp = False idx = -1 for i in range(len(nums1)): if nums1[i] != nums2[i]: if temp: return False temp = True idx = i if idx == -1 or abs(nums1[idx]-nums2[idx]) <= k: return True return False nums1 = [5,7,11] nums2 = [5,5,11] k = 8 print(solve(nums1, nums2, k))
Input
[5,7,11], [5,5,11], 8
Output
True
Advertisements