Find a pair of elements swapping which makes sum of two arrays same - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Find a pair of elements swapping which makes sum of two arrays same
Count distinct elements in every window of size k
Convert a given tree to its Sum Tree
Change a Binary Tree so that every node stores sum of all nodes in left subtree
Convert a Binary Tree into its Mirror Tree
Check if two trees are Mirror
Iterative method to check if two trees are mirror of each other
Iterative function to check if two trees are identical
Write Code to Determine if Two Trees are Identical
Write a Program to Find the Maximum Depth or Height of a Tree
Iterative Method to find Height of Binary Tree
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorff’s algorithm for Knight’s tour problem
The Knight’s tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Tree Traversals (Inorder, Preorder and Postorder)
Arrays in Java
Write a program to reverse an array or string
Largest Sum Contiguous Subarray
Program for array rotation
Arrays in C/C++
Find a pair of elements swapping which makes sum of two arrays same
Count distinct elements in every window of size k
Convert a given tree to its Sum Tree
Change a Binary Tree so that every node stores sum of all nodes in left subtree
Convert a Binary Tree into its Mirror Tree
Check if two trees are Mirror
Iterative method to check if two trees are mirror of each other
Iterative function to check if two trees are identical
Write Code to Determine if Two Trees are Identical
Write a Program to Find the Maximum Depth or Height of a Tree
Iterative Method to find Height of Binary Tree
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorff’s algorithm for Knight’s tour problem
The Knight’s tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Tree Traversals (Inorder, Preorder and Postorder)
Arrays in Java
Write a program to reverse an array or string
Largest Sum Contiguous Subarray
Program for array rotation
Arrays in C/C++
Difficulty Level :
Medium
Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.Examples:  
Input: A[] = {4, 1, 2, 1, 1, 2}, B[] = (3, 6, 3, 3) Output: {1, 3} Sum of elements in A[] = 11 Sum of elements in B[] = 15 To get same sum from both arrays, we can swap following values: 1 from A[] and 3 from B[]Input: A[] = {5, 7, 4, 6}, B[] = {1, 2, 3, 8} Output: 6 2
 
Method 1 (Naive Implementation): Iterate through the arrays and check all pairs of values. Compare new sums or look for a pair with that difference.   
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
Java
Python3
C#
PHP
Javascript
// CPP code naive solution to find a pair swapping// which makes sum of arrays sum.#include <iostream>using namespace std; // Function to calculate sum of elements of arrayint getSum(int X[], int n){    int sum = 0;    for (int i = 0; i < n; i++)        sum += X[i];    return sum;} void findSwapValues(int A[], int n, int B[], int m){    // Calculation of sums from both arrays    int sum1 = getSum(A, n);    int sum2 = getSum(B, m);     // Look for val1 and val2, such that    // sumA - val1 + val2 = sumB - val2 + val1    int newsum1, newsum2, val1, val2;    for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {            newsum1 = sum1 - A[i] + B[j];            newsum2 = sum2 - B[j] + A[i];            if (newsum1 == newsum2) {                val1 = A[i];                val2 = B[j];            }        }    }     cout << val1 << " " << val2;} // Driver codeint main(){    int A[] = { 4, 1, 2, 1, 1, 2 };    int n = sizeof(A) / sizeof(A[0]);    int B[] = { 3, 6, 3, 3 };    int m = sizeof(B) / sizeof(B[0]);     // Call to function    findSwapValues(A, n, B, m);    return 0;}
// Java program to find a pair swapping// which makes sum of arrays sumimport java.io.*; class GFG{    // Function to calculate sum of elements of array    static int getSum(int X[], int n)    {        int sum = 0;        for (int i = 0; i < n; i++)            sum += X[i];        return sum;    }         // Function to prints elements to be swapped    static void findSwapValues(int A[], int n, int B[], int m)    {        // Calculation of sums from both arrays        int sum1 = getSum(A, n);        int sum2 = getSum(B, m);          // Look for val1 and val2, such that        // sumA - val1 + val2 = sumB - val2 + val1        int newsum1, newsum2, val1 = 0, val2 = 0;        for (int i = 0; i < n; i++)        {            for (int j = 0; j < m; j++)            {                newsum1 = sum1 - A[i] + B[j];                newsum2 = sum2 - B[j] + A[i];                if (newsum1 == newsum2)                {                    val1 = A[i];                    val2 = B[j];                }            }        }          System.out.println(val1+" "+val2);    }         // driver program    public static void main (String[] args)    {        int A[] = { 4, 1, 2, 1, 1, 2 };        int n = A.length;        int B[] = { 3, 6, 3, 3 };        int m = B.length;          // Call to function        findSwapValues(A, n, B, m);    }} // Contributed by Pramod Kumar
# Python code naive solution to find a pair swapping# which makes sum of lists sum. # Function to calculate sum of elements of listdef getSum(X):    sum=0    for i in X:        sum+=i    return sum # Function to prints elements to be swappeddef findSwapValues(A,B):    # Calculation if sums from both lists    sum1=getSum(A)    sum2=getSum(B)     # Boolean variable used to reduce further iterations    # after the pair is found    k=False     # Lool for val1 and val2, such that    # sumA - val1 + val2 = sumB -val2 + val1    val1,val2=0,0    for i in A:        for j in B:            newsum1=sum1-i+j            newsum2=sum2-j+i                         if newsum1 ==newsum2:                val1=i                val2=j                # Set to True when pair is found                k=True                break        # If k is True, it means pair is found.        # So, no further iterations.        if k==True:            break    print (val1,val2)    return  # Driver codeA=[4,1,2,1,1,2]B=[3,6,3,3] # Call to functionfindSwapValues(A,B) # code contributed by sachin bisht
// C# program to find a pair swapping// which makes sum of arrays sumusing System; class GFG{// Function to calculate sum// of elements of arraystatic int getSum(int[] X, int n){    int sum = 0;    for (int i = 0; i < n; i++)        sum += X[i];    return sum;} // Function to prints elements// to be swappedstatic void findSwapValues(int[] A, int n,                           int[] B, int m){    // Calculation of sums from    // both arrays    int sum1 = getSum(A, n);    int sum2 = getSum(B, m);     // Look for val1 and val2, such that    // sumA - val1 + val2 = sumB - val2 + val1    int newsum1, newsum2,          val1 = 0, val2 = 0;    for (int i = 0; i < n; i++)    {        for (int j = 0; j < m; j++)        {            newsum1 = sum1 - A[i] + B[j];            newsum2 = sum2 - B[j] + A[i];            if (newsum1 == newsum2)            {                val1 = A[i];                val2 = B[j];            }        }    }     Console.Write(val1 + " " + val2);} // Driver Codepublic static void Main (){    int[] A = { 4, 1, 2, 1, 1, 2 };    int n = A.Length;    int[] B = { 3, 6, 3, 3 };    int m = B.Length;     // Call to function    findSwapValues(A, n, B, m);}} // This code is contributed// by ChitraNayal
<?php// PHP code naive solution to find// a pair swapping which makes sum// of arrays sum. // Function to calculate sum of// elements of arrayfunction getSum($X, $n){    $sum = 0;    for ($i = 0; $i < $n; $i++)        $sum += $X[$i];    return $sum;} function findSwapValues($A, $n, $B, $m){    // Calculation of sums from both arrays    $sum1 = getSum($A, $n);    $sum2 = getSum($B, $m);     // Look for val1 and val2, such that    // sumA - val1 + val2 = sumB - val2 + val1    for ($i = 0; $i < $n; $i++)    {        for ($j = 0; $j < $m; $j++)        {            $newsum1 = $sum1 - $A[$i] + $B[$j];            $newsum2 = $sum2 - $B[$j] + $A[$i];            if ($newsum1 == $newsum2)            {                $val1 = $A[$i];                $val2 = $B[$j];            }        }    }     echo $val1 . " " . $val2;} // Driver code$A = array(4, 1, 2, 1, 1, 2 );$n = sizeof($A);$B = array(3, 6, 3, 3 );$m = sizeof($B); // Call to functionfindSwapValues($A, $n, $B, $m); // This code is contributed// by Akanksha Rai?>
<script>// Javascript program to find a pair swapping// which makes sum of arrays sum         // Function to calculate sum of elements of array    function  getSum(X,n)    {        let sum = 0;        for (let i = 0; i < n; i++)            sum += X[i];        return sum;    }         // Function to prints elements to be swapped    function findSwapValues(A,n,B,m)    {        // Calculation of sums from both arrays        let sum1 = getSum(A, n);        let sum2 = getSum(B, m);            // Look for val1 and val2, such that        // sumA - val1 + val2 = sumB - val2 + val1        let newsum1, newsum2, val1 = 0, val2 = 0;        for (let i = 0; i < n; i++)        {            for (let j = 0; j < m; j++)            {                newsum1 = sum1 - A[i] + B[j];                newsum2 = sum2 - B[j] + A[i];                if (newsum1 == newsum2)                {                    val1 = A[i];                    val2 = B[j];                }            }        }            document.write(val1+" "+val2);    }         // driver program    let A=[4, 1, 2, 1, 1, 2];    let n = A.length;    let B=[3, 6, 3, 3 ];    let m = B.length;    // Call to function    findSwapValues(A, n, B, m);         //This code is contributed by avanitrachhadiya2155     </script>
1 3
Time Complexity :- O(n*m)  Method 2 -> Other Naive implementation  
We are looking for two values, a and b, such that: 
sumA - a + b = sumB - b + a
    2a - 2b  = sumA - sumB
      a - b  = (sumA - sumB) / 2
Therefore, we’re looking for two values that have a specific target difference: (sumA – sumB) / 2.   
C++
Java
Python3
C#
PHP
Javascript
// CPP code for naive implementation#include <iostream>using namespace std; // Function to calculate sum of elements of arrayint getSum(int X[], int n){    int sum = 0;    for (int i = 0; i < n; i++)        sum += X[i];    return sum;} // Function to calculate : a - b = (sumA - sumB) / 2int getTarget(int A[], int n, int B[], int m){    // Calculation of sums from both arrays    int sum1 = getSum(A, n);    int sum2 = getSum(B, m);     // because that the target must be an integer    if ((sum1 - sum2) % 2 != 0)        return 0;    return ((sum1 - sum2) / 2);} void findSwapValues(int A[], int n, int B[], int m){    int target = getTarget(A, n, B, m);    if (target == 0)        return;     // Look for val1 and val2, such that    // val1 - val2 = (sumA - sumB) / 2    int val1, val2;    for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {            if (A[i] - B[j] == target) {                val1 = A[i];                val2 = B[j];            }        }    }     cout << val1 << " " << val2;} // Driver codeint main(){    int A[] = { 4, 1, 2, 1, 1, 2 };    int n = sizeof(A) / sizeof(A[0]);    int B[] = { 3, 6, 3, 3 };    int m = sizeof(B) / sizeof(B[0]);     // Call to function    findSwapValues(A, n, B, m);    return 0;}
// Java program to find a pair swapping// which makes sum of arrays sumimport java.io.*; class GFG{    // Function to calculate sum of elements of array    static int getSum(int X[], int n)    {        int sum = 0;        for (int i = 0; i < n; i++)            sum += X[i];        return sum;    }         // Function to calculate : a - b = (sumA - sumB) / 2    static int getTarget(int A[], int n, int B[], int m)    {        // Calculation of sums from both arrays        int sum1 = getSum(A, n);        int sum2 = getSum(B, m);          // because that the target must be an integer        if ((sum1 - sum2) % 2 != 0)            return 0;        return ((sum1 - sum2) / 2);    }         // Function to prints elements to be swapped    static void findSwapValues(int A[], int n, int B[], int m)    {        int target = getTarget(A, n, B, m);        if (target == 0)            return;          // Look for val1 and val2, such that        // val1 - val2 = (sumA - sumB) / 2        int val1 = 0, val2 = 0;        for (int i = 0; i < n; i++)        {            for (int j = 0; j < m; j++)            {                if (A[i] - B[j] == target)                {                    val1 = A[i];                    val2 = B[j];                }            }        }        System.out.println(val1+" "+val2);    }         // driver program    public static void main (String[] args)    {        int A[] = { 4, 1, 2, 1, 1, 2 };        int n = A.length;        int B[] = { 3, 6, 3, 3 };        int m = B.length;          // Call to function        findSwapValues(A, n, B, m);    }} // Contributed by Pramod Kumar
# Python Code for naive implementation # Function to calculate sum of elements of listdef getSum(X):    sum=0    for i in X:        sum+=i    return sum # Function to calculate : a-b = (sumA - sumB) / 2def getTarget(A,B):     #Calculations of sums from both lists    sum1=getSum(A)    sum2=getSum(B)     # Because the target must be an integer    if( (sum1-sum2)%2!=0):        return 0    return (sum1-sum2)//2  def findSwapValues(A,B):    target=getTarget(A,B)    if target==0:        return     # Boolean variable used to reduce further iterations    # after the pair is found    flag=False     # Look for val1 and val2, such that    # val1 - val2 = (sumA -sumB) /2    val1,val2=0,0    for i in A:        for j in B:                         if i-j == target:                val1=i                val2=j                # Set to True when pair is found                flag=True                break        if flag==True:            break    print (val1,val2)    return  # Driver codeA=[4,1,2,1,1,2]B=[3,6,3,3] # Call to functionfindSwapValues(A,B) # code contributed by sachin bisht
// C# program to find a pair swapping// which makes sum of arrays sumusing System; class GFG{     // Function to calculate sum of elements of array    static int getSum(int []X, int n)    {        int sum = 0;        for (int i = 0; i < n; i++)            sum += X[i];        return sum;    }          // Function to calculate : a - b = (sumA - sumB) / 2    static int getTarget(int []A, int n, int []B, int m)    {        // Calculation of sums from both arrays        int sum1 = getSum(A, n);        int sum2 = getSum(B, m);           // because that the target must be an integer        if ((sum1 - sum2) % 2 != 0)            return 0;        return ((sum1 - sum2) / 2);    }          // Function to prints elements to be swapped    static void findSwapValues(int []A, int n, int []B, int m)    {        int target = getTarget(A, n, B, m);        if (target == 0)            return;           // Look for val1 and val2, such that        // val1 - val2 = (sumA - sumB) / 2        int val1 = 0, val2 = 0;        for (int i = 0; i < n; i++)        {            for (int j = 0; j < m; j++)            {                if (A[i] - B[j] == target)                {                    val1 = A[i];                    val2 = B[j];                }            }        }        Console.Write(val1+" "+val2);    }          // Driver code    public static void Main ()    {        int []A = { 4, 1, 2, 1, 1, 2 };        int n = A.Length;        int []B = { 3, 6, 3, 3 };        int m = B.Length;           // Call to function        findSwapValues(A, n, B, m);    }} /*This code is contributed by 29AjayKumar*/
<?php// PHP code for naive implementation // Function to calculate sum// of elements of arrayfunction getSum($X, $n){    $sum = 0;    for ($i = 0; $i < $n; $i++)        $sum += $X[$i];    return $sum;} // Function to calculate :// a - b = (sumA - sumB) / 2function getTarget($A, $n, $B, $m){    // Calculation of sums from    // both arrays    $sum1 = getSum($A, $n);    $sum2 = getSum($B, $m);     // because that the target    // must be an integer    if (($sum1 - $sum2) % 2 != 0)        return 0;    return (($sum1 - $sum2) / 2);} function findSwapValues($A, $n, $B, $m){    $target = getTarget($A, $n, $B, $m);    if ($target == 0)        return;     // Look for val1 and val2, such that    // val1 - val2 = (sumA - sumB) / 2    for ($i = 0; $i < $n; $i++)    {        for ($j = 0; $j < $m; $j++)        {            if ($A[$i] - $B[$j] == $target)            {                $val1 = $A[$i];                $val2 = $B[$j];            }        }    }     echo $val1 . " " . $val2;} // Driver code$A = array(4, 1, 2, 1, 1, 2);$n = sizeof($A);$B = array(3, 6, 3, 3);$m = sizeof($B); // Call to functionfindSwapValues($A, $n, $B, $m); // This code is contributed// by Akanksha Rai?>
<script>// Javascript program to find a pair swapping// which makes sum of arrays sum // Function to calculate sum of elements of arrayfunction getSum(X,n){    let sum = 0;        for (let i = 0; i < n; i++)            sum += X[i];        return sum;} // Function to calculate : a - b = (sumA - sumB) / 2function getTarget(A,n,B,m){    // Calculation of sums from both arrays        let sum1 = getSum(A, n);        let sum2 = getSum(B, m);           // because that the target must be an integer        if ((sum1 - sum2) % 2 != 0)            return 0;        return ((sum1 - sum2) / 2);} // Function to prints elements to be swappedfunction findSwapValues(A,n,B,m){    let target = getTarget(A, n, B, m);        if (target == 0)            return;           // Look for val1 and val2, such that        // val1 - val2 = (sumA - sumB) / 2        let val1 = 0, val2 = 0;        for (let i = 0; i < n; i++)        {            for (let j = 0; j < m; j++)            {                if (A[i] - B[j] == target)                {                    val1 = A[i];                    val2 = B[j];                }            }        }        document.write(val1+" "+val2+"<br>");} // driver programlet A=[4, 1, 2, 1, 1, 2];let n = A.length;let B=[3, 6, 3, 3 ];let m = B.length;// Call to functionfindSwapValues(A, n, B, m);   // This code is contributed by ab2127</script>
1 3
Time Complexity :- O(n*m)  Method 3 -> Optimized Solution :-  
Sort the arrays.
Traverse both array simultaneously and do following for every pair. If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.If it is too big then, make it smaller by moving b to a bigger value.If it’s just right, return this pair.
If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.If it is too big then, make it smaller by moving b to a bigger value.If it’s just right, return this pair.
If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.
If it is too big then, make it smaller by moving b to a bigger value.
If it’s just right, return this pair.
Below image is a dry run of the above approach: 
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// CPP code for optimized implementation#include <bits/stdc++.h>using namespace std; // Returns sum of elements in X[]int getSum(int X[], int n){    int sum = 0;    for (int i = 0; i < n; i++)        sum += X[i];    return sum;} // Finds value of// a - b = (sumA - sumB) / 2int getTarget(int A[], int n, int B[], int m){    // Calculation of sums from both arrays    int sum1 = getSum(A, n);    int sum2 = getSum(B, m);     // because that the target must be an integer    if ((sum1 - sum2) % 2 != 0)        return 0;    return ((sum1 - sum2) / 2);} // Prints elements to be swappedvoid findSwapValues(int A[], int n, int B[], int m){    // Call for sorting the arrays    sort(A, A + n);    sort(B, B + m);     // Note that target can be negative    int target = getTarget(A, n, B, m);     // target 0 means, answer is not possible    if (target == 0)        return;     int i = 0, j = 0;    while (i < n && j < m) {        int diff = A[i] - B[j];        if (diff == target) {            cout << A[i] << " " << B[j];            return;        }         // Look for a greater value in A[]        else if (diff < target)            i++;         // Look for a greater value in B[]        else            j++;    }} // Driver codeint main(){    int A[] = { 4, 1, 2, 1, 1, 2 };    int n = sizeof(A) / sizeof(A[0]);     int B[] = { 1, 6, 3, 3 };    int m = sizeof(B) / sizeof(B[0]);     findSwapValues(A, n, B, m);    return 0;}
// Java code for optimized implementationimport java.io.*;import java.util.*; class GFG{    // Function to calculate sum of elements of array    static int getSum(int X[], int n)    {        int sum = 0;        for (int i = 0; i < n; i++)            sum += X[i];        return sum;    }         // Function to calculate : a - b = (sumA - sumB) / 2    static int getTarget(int A[], int n, int B[], int m)    {        // Calculation of sums from both arrays        int sum1 = getSum(A, n);        int sum2 = getSum(B, m);          // because that the target must be an integer        if ((sum1 - sum2) % 2 != 0)            return 0;        return ((sum1 - sum2) / 2);    }         // Function to prints elements to be swapped    static void findSwapValues(int A[], int n, int B[], int m)    {        // Call for sorting the arrays        Arrays.sort(A);        Arrays.sort(B);          // Note that target can be negative        int target = getTarget(A, n, B, m);          // target 0 means, answer is not possible        if (target == 0)            return;          int i = 0, j = 0;        while (i < n && j < m)        {            int diff = A[i] - B[j];            if (diff == target)            {                System.out.println(A[i]+" "+B[i]);                return;            }              // Look for a greater value in A[]            else if (diff < target)                i++;              // Look for a greater value in B[]            else                j++;        }    }         // driver program    public static void main (String[] args)    {        int A[] = { 4, 1, 2, 1, 1, 2 };        int n = A.length;        int B[] = { 3, 6, 3, 3 };        int m = B.length;          // Call to function        findSwapValues(A, n, B, m);    }} // Contributed by Pramod Kumar
# Python code for optimized implementation #Returns sum of elements in listdef getSum(X):    sum=0    for i in X:        sum+=i    return sum # Finds value of# a - b = (sumA - sumB) / 2def getTarget(A,B):    # Calculations of sumd from both lists    sum1=getSum(A)    sum2=getSum(B)     # Because that target must be an integer    if( (sum1-sum2)%2!=0):        return 0    return (sum1-sum2)//2 # Prints elements to be swappeddef findSwapValues(A,B):    # Call for sorting the lists    A.sort()    B.sort()     #Note that target can be negative    target=getTarget(A,B)     # target 0 means, answer is not possible    if(target==0):        return    i,j=0,0    while(i<len(A) and j<len(B)):        diff=A[i]-B[j]        if diff == target:            print (A[i],B[j])            return        # Look for a greater value in list A        elif diff <target:            i+=1        # Look for a greater value in list B        else:            j+=1 A=[4,1,2,1,1,2]B=[3,6,3,3] findSwapValues(A,B) #code contributed by sachin bisht
// C# code for optimized implementationusing System; class GFG{    // Function to calculate sum of elements of array    static int getSum(int []X, int n)    {        int sum = 0;        for (int i = 0; i < n; i++)            sum += X[i];        return sum;    }         // Function to calculate : a - b = (sumA - sumB) / 2    static int getTarget(int []A, int n, int []B, int m)    {        // Calculation of sums from both arrays        int sum1 = getSum(A, n);        int sum2 = getSum(B, m);         // because that the target must be an integer        if ((sum1 - sum2) % 2 != 0)            return 0;        return ((sum1 - sum2) / 2);    }         // Function to prints elements to be swapped    static void findSwapValues(int []A, int n, int []B, int m)    {        // Call for sorting the arrays        Array.Sort(A);        Array.Sort(B);         // Note that target can be negative        int target = getTarget(A, n, B, m);         // target 0 means, answer is not possible        if (target == 0)            return;         int i = 0, j = 0;        while (i < n && j < m)        {            int diff = A[i] - B[j];            if (diff == target)            {                Console.WriteLine(A[i]+" "+B[i]);                return;            }             // Look for a greater value in A[]            else if (diff < target)                i++;             // Look for a greater value in B[]            else                j++;        }    }         // Driver code    public static void Main (String[] args)    {        int []A = { 4, 1, 2, 1, 1, 2 };        int n = A.Length;        int []B = { 3, 6, 3, 3 };        int m = B.Length;         // Call to function        findSwapValues(A, n, B, m);    }} // This code has been contributed by 29AjayKumar
<script>// Javascript code for optimized implementation // Function to calculate sum of elements of arrayfunction getSum(X,n){    let sum = 0;        for (let i = 0; i < n; i++)            sum += X[i];        return sum;} // Function to calculate : a - b = (sumA - sumB) / 2function getTarget(A,n,B,m){    // Calculation of sums from both arrays        let sum1 = getSum(A, n);        let sum2 = getSum(B, m);           // because that the target must be an integer        if ((sum1 - sum2) % 2 != 0)            return 0;        return ((sum1 - sum2) / 2);} // Function to prints elements to be swappedfunction findSwapValues(A,n,B,m){    // Call for sorting the arrays        A.sort(function(a,b){return a-b;});        B.sort(function(a,b){return a-b;});                   // Note that target can be negative        let target = getTarget(A, n, B, m);                   // target 0 means, answer is not possible        if (target == 0)            return;           let i = 0, j = 0;        while (i < n && j < m)        {            let diff = A[i] - B[j];                         if (diff == target)            {                document.write(A[i]+" "+B[j]);                return;            }               // Look for a greater value in A[]            else if (diff < target)                i++;               // Look for a greater value in B[]            else                j++;        }} // driver programlet A=[4, 1, 2, 1, 1, 2 ];let n = A.length;let B=[3, 6, 3, 3 ];let m = B.length;// Call to functionfindSwapValues(A, n, B, m);  // This code is contributed by unknown2108</script>
2 3
Time Complexity :- If arrays are sorted : O(n + m) If arrays aren’t sorted : O(nlog(n) + mlog(m)) Method 4 (Hashing) We can solve this problem in O(m+n) time and O(m) auxiliary space. Below are algorithmic steps.  
// assume array1 is small i.e. (m < n)
// where m is array1.length and n is array2.length
1. Find sum1(sum of small array elements) ans sum2
  (sum of larger array elements). // time O(m+n)
2. Make a hashset for small array(here array1).
3. Calculate diff as (sum1-sum2)/2.
4. Run a loop for array2
     for (int i equal to 0 to n-1)
       if (hashset contains (array2[i]+diff))
           print array2[i]+diff and array2[i]
           set flag  and break;
5. If flag is unset then there is no such kind of 
pair.
Thanks to nicky khan for suggesting method 4.This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Another Approach:
We can also solve this problem in linear time using hashing. Let us assume that sum of the elements of the first array a[] is s1, and of the second array b[] is s2. Also suppose that a pair to be swapped is (p, q), where p belongs to a[] and q belongs to b[]. Therefore, we have the equation s1 – p + q = s2 – q + p, i.e. 2q = s2 – s1 + 2p. Since both 2p and 2q are even integers, the difference s2 – s1 must be an even integer too. So, given any p, our aim is to find an appropriate q satisfying the above conditions.  
Below is an implementation of the said approach:
C++
#include <bits/stdc++.h>using namespace std;void findSwapValues(int a[], int m, int b[], int n);int main(){    int a[] = { 4, 1, 2, 1, 1, 2 }, b[] = { 1, 6, 3, 3 };    int m, n;    m = sizeof(a) / sizeof(int),    n = sizeof(b) / sizeof(int);    findSwapValues(a, m, b, n);    return 0;}void findSwapValues(int a[], int m, int b[], int n){    unordered_set<int> x,        y; /* Unordered sets (and unordered maps) are              implemented internally using hash tables; they              support dictionary operations (i.e. search,              insert, delete) in O(1) time on an average. */    unordered_set<int>::iterator p, q;    int s1, s2;    int i;    s1 = 0;    for (i = 0; i < m;         i++) /* Determining sum s1 of the elements of array                 a[], and simultaneously inserting the array                 elements in the unordered set. */        s1 += a[i], x.insert(a[i]);    s2 = 0;    for (i = 0; i < n; i++)        s2 += b[i], y.insert(b[i]);    if ((s1 - s2) % 2) /* Checking if difference between the                                              two array sums                          is even or not. */    {        printf("No such values exist.\n");        return;    }    for (p = x.begin(); p != x.end(); p++) {        q = y.find(            ((s2 - s1) + 2 * *p)            / 2); // Finding q for a given p in O(1) time.        if (q != y.end()) {            printf("%d %d\n", *p, *q);            return;        }    }    printf("No such values exist.\n");}
2 3
Time complexity of the above code is O(m + n), where m and n respectively represent the sizes of the two input arrays, and space complexity O(s + t), where s and t respectively represent the number of distinct elements present in the two input arrays.
ukasp
Akanksha_Rai
princiraj1992
29AjayKumar
avanitrachhadiya2155
arghyamukherjee
ab2127
unknown2108
surinderdawra388
simmytarika5
amartyaghoshgfg
Amazon
Arrays
Hash
Sorting
Amazon
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)