Two-Sum Problem एक सामान्य साक्षात्कार प्रश्न है, और यह सबसेट योग समस्या का एक रूपांतर है। सबसेट योग समस्या के लिए एक लोकप्रिय गतिशील प्रोग्रामिंग समाधान है, लेकिन दो योग समस्या के लिए हम वास्तव में एक एल्गोरिदम लिख सकते हैं जो O(n) समय में चलता है। चुनौती दो पूर्णांकों के सभी युग्मों को एक अवर्गीकृत सरणी में खोजने की है जो किसी दिए गए S तक योग करता है।
Two-Sum Problem एक लीटकोड क्लासिक है जिसमें विभिन्न मूलभूत समाधान शामिल हैं। इन समाधानों के निर्माण में विभिन्न तकनीकों को समझना शामिल है, जिनके बारे में मैं बस एक क्षण में आगे चर्चा करूंगा। हालाँकि, जारी रखने से पहले, मैं अनुशंसा करता हूँ कि आप समस्या को पूरी तरह से समझने के लिए arrays, hash maps, time-complexity, and space-complexity के बारे में जान ले।
What is the two-sum problem?
दी गई Integer Array मैं से दो संख्याओं के Indexes return करो जिनका योग दिए गए Target के बराबर हैं।
ध्यान दें कि आप दो बार एक ही Array Integer का उपयोग नहीं कर सकते हैं, लेकिन आप मान सकते हैं कि प्रत्येक परीक्षण मामले के लिए केवल एक ही समाधान होगा।
Two-Sum उदाहरण के लिए, यदि Array [3, 5, 2, -4, 8] हैं, और Target योग 7 हैं, your program should return [1, 2]
- Input: nums = [1,4,10,-3], target = 14
- Output: [1,2] or [2,1] # 4 + 10 = 14
- Input: nums = [9,5,1,23], target = 10
- Output: [0,2] or [2,0] # 9 + 1 = 10
- Input: nums = [1,-2,5,10], target = -1
- Output: [0,1] or [1,0] # 1 + -2 = -1
जैसा कि आप उपरोक्त Test Cases मैं देख सकते हैं, प्रत्येक Test Case में लौटाया गया आउटपुट दो संख्याओं के Indexes की एक Array है जिनका योग Target Sum के बराबर हैं। ध्यान दें कि Solution Array में मौजूद Indexes का क्रम इस समस्या के लिए महत्वपूर्ण नहीं है।
Approach
Two-Sum LeetCode समस्या का विश्लेषण करने के बाद, अब समाधान के बारे में सोचने का समय आ गया है।
#1 Naive Approach To Solve Two Sum Leetcode Problem
पहला solution जो दिमाग में आता है वह है –
- एक Element लो
- इस Element को हर दूसरे Element के साथ जोड़ें
- जोड़ने के बाद, प्राप्त Sum को Target Sum के साथ Compare करे
- यदि प्राप्त Sum Target Sum के बराबर है, तो इन दो Elements के Indexes return करे
- यदि प्राप्त Sum Target Sum के बराबर नहीं है, तो हम Next Element के लिए Check करते हैं
Various Solution Using Naive Approach
Using C++
using namespace std;
// Function to find and print pair
bool chkPair(int A[], int size, int x)
{
for (int i = 0; i < (size - 1); i++) {
for (int j = (i + 1); j < size; j++) {
if (A[i] + A[j] == x) {
return 1;
}
}
}
return 0;
}
// Driver code
int main()
{
int A[] = { 0, -1, 2, -3, 1 };
int x = -2;
int size = sizeof(A) / sizeof(A[0]);
if (chkPair(A, size, x)) {
cout << "Yes" << endl;
}
else {
cout << "No" << x << endl;
}
return 0;
}C++Using C
/*
* This C program tells if there exists a pair in array
* whose sum results in x.
*/
#include
// Function to find and print pair
int chkPair(int A[], int size, int x)
{
for (int i = 0; i < (size - 1); i++) {
for (int j = (i + 1); j < size; j++) {
if (A[i] + A[j] == x) {
return 1;
}
}
}
return 0;
}
int main(void)
{
int A[] = { 0, -1, 2, -3, 1 };
int x = -2;
int size = sizeof(A) / sizeof(A[0]);
if (chkPair(A, size, x)) {
printf("Yes\n");
}
else {
printf("No\n");
}
return 0;
}CUsing Java
// Java program to check if there exists a pair
// in array whose sum results in x.
import java.io.*;
class TwoSum{
// Function to find and print pair
static boolean chkPair(int A[], int size, int x)
{
for (int i = 0; i < (size - 1); i++) {
for (int j = (i + 1); j < size; j++) {
if (A[i] + A[j] == x) {
return true;
}
}
}
return false;
}
public static void main(String[] args)
{
int A[] = { 0, -1, 2, -3, 1 };
int x = -2;
int size = A.length;
if (chkPair(A, size, x)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
JavaUsing Python
# This python program tells if there exists a pair in array whose sum results in x.
# Function to find and print pair
def chkPair(A, size, x):
for i in range(0, size - 1):
for j in range(i + 1, size):
if (A[i] + A[j] == x):
return 1
return 0
if __name__ == "__main__":
A = [0, -1, 2, -3, 1]
x = -2
size = len(A)
if (chkPair(A, size, x)):
print("Yes")
else:
print("No")PythonUsing C#
// C# program to check if there exists a pair
// in array whose sum results in x.
using System;
class TwoSum{
// Function to find and print pair
static bool chkPair(int[] A, int size, int x)
{
for (int i = 0; i < (size - 1); i++) {
for (int j = (i + 1); j < size; j++) {
if (A[i] + A[j] == x) {
return true;
}
}
}
return false;
}
public static void Main()
{
int[] A = { 0, -1, 2, -3, 1 };
int x = -2;
int size = A.Length;
if (chkPair(A, size, x)) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
}
C#Using JavaScript
function chkPair(A , size , x) {
for (i = 0; i < (size - 1); i++) {
for (j = (i + 1); j < size; j++) {
if (A[i] + A[j] == x) {
document.write("Pair with a given sum " + x + " is (" + A[i] + ", " + A[j] + ")");
return true;
}
}
}
return false;
}
let A = [ 0, -1, 2, -3, 1 ];
let x = -2;
let size = A.length;
if (chkPair(A, size, x)) {
document.write("<br/>Valid pair exists");
}
else {
document.write("<br/>No valid pair exists for " + x);
}
JavaScriptUsing Go
package main
import ("fmt")
func twoSum(nums [5]int, target int) {
var flag bool = false
result:=make([]int,2)
for i:=0;i<len(nums)-1;i++{
for j:=i+1;j<len(nums);j++{
if nums[i]+nums[j]==target{
result[0]=nums[i]
result[1]=nums[j]
flag = true;
}
}
}
if(flag == false){
fmt.Println("No")
}else {
fmt.Printf( "Yes")
}
}
func main() {
arr2 := [5]int{0, -1, 2, -3, 1}
var x int = -2
twoSum(arr2, x)
}Goआइए Two-Sum Solution की Time और Space Complexity का विश्लेषण करें।
Time Complexity For Two-Sum Problem :
मान लीजिए कि Array में n Elements हैं –
पहले Element के लिए – हम (n – 1) Elements की जाँच करेंगे
दूसरे Element के लिए – हम (n – 2) Elements की जाँच करेंगे
तीसरे Element के लिए – हम (n – 3) Elements की जाँच करेंगे
और इसी तरह…
इस प्रकार, कुल iterations होगी – [(n – 1) + (n – 2) + (n – 3) + … + 2 + 1]
यदि हम उपरोक्त व्यंजक को सरल करें तो हमें प्राप्त होगा –
n * (n – 1) / 2 = n2 – 2n ≈ n2
इसलिए Time Complexity = O(n2)
Space Complexity For Two-Sum Problem:
चूँकि हम किसी अतिरिक्त Data Structure का उपयोग नहीं कर रहे हैं इसलिए हमारी Space Complexity O(1) होगी।
यह दृष्टिकोण सरल और सहज है लेकिन इसमें द्विघात समय (Quadratic Time ) लगता है जो बड़े इनपुट के लिए खराब है। आइए देखें कि क्या हमारे पास इस समस्या को हल करने के लिए कोई कारगर तरीका है।
Learn Fizz-Buzz Problem Solution Click Here
#2 Hashing Approach To Solve Two-Sum Leetcode Problem
जब हम समस्या का विश्लेषण कर रहे थे, तो हमें निम्नलिखित समीकरण मिले
C = A + B
लेकिन हम उपरोक्त समीकरण को इस प्रकार लिख सकते हैं
B = C - A
इस समीकरण को लिखने का लाभ यह है कि अब हम Array को केवल एक बार Iterate कर सकते हैं और Target(A) और Current Element(A के अंतर की गणना कर सकते हैं और अन्य Element(B) को खोज सकते हैं।
- Array को लूप करें
- जांचें कि क्या हमने पहले Current Element का सामना किया है
- यदि हाँ, तो हम इस Element के Index और Target और Current Element के Diffrence के Index को वापस कर देंगे। हम इस Element का सामना तभी करेंगे जब हमने Target के अंतर को Save किया हो और वह Element जो Current Element में जोड़ने पर Target Sum को ही देता है।
- यदि नहीं, तो हम Target और Current Element के बीच के अंतर को Save कर लेंगे।
- प्रक्रिया को दोहराएं
चूँकि हमें अपने अंतर को संग्रहित करने की आवश्यकता है, हमें एक डेटा Structure की आवश्यकता है जो अंतर और उसके संबंधित सूचकांक (Indexes) को संग्रहीत कर सके।
तो आपको क्या लगता है, कौन सा डेटा Structure हमारी मदद कर सकता है? बेशक, हमें एक Map की आवश्यकता है जहां हम Difference को Key के रूप में और संबंधित Index को Value के रूप में संग्रहीत करेंगे।
Various Solution Using Naive Approach
Using Java
package org.redquark.tutorials.leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
// Array to store result
int[] result = new int[2];
// This map will store the difference and the corresponding index
Map<Integer, Integer> map = new HashMap<>();
// Loop through the entire array
for (int i = 0; i < nums.length; i++) {
// If we have seen the current element before
// It means we have already encountered the other number of the pair
if (map.containsKey(nums[i])) {
// Index of the current element
result[0] = i;
// Index of the other element of the pair
result[1] = map.get(nums[i]);
}
// If we have not seen the current before
// It means we have not yet encountered any number of the pair
else {
// Save the difference of the target and the current element
// with the index of the current element
map.put(target - nums[i], i);
}
}
return result;
}
}JavaUsing Python
from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
# List to store results
result = []
# Dictionary to store the difference and its index
index_map = {}
# Loop for each element
for i, n in enumerate(nums):
# Difference which needs to be checked
difference = target - n
if difference in index_map:
result.append(i)
result.append(index_map[difference])
break
else:
index_map[n] = i
return resultPythonUsing JavaScript
var twoSum = function (nums, target) {
// Array to store the result
result = [];
// Map to store the difference and its index
index_map = new Map();
// Loop for each element in the array
for (let i = 0; i < nums.length; i++) {
let difference = target - nums[i];
if (index_map.has(difference)) {
result[0] = i;
result[1] = index_map.get(difference);
break;
} else {
index_map.set(nums[i], i);
}
}
return result;
};JavaScriptUsing Kotlin
package org.redquark.tutorials.leetcode
fun twoSum(nums: IntArray, target: Int): IntArray {
// Array to store result
val result = IntArray(2)
// This map will store the difference and the corresponding index
val map: MutableMap<Int, Int> = HashMap()
// Loop through the entire array
for (i in nums.indices) {
// If we have seen the current element before
// It means we have already encountered the other number of the pair
if (map.containsKey(nums[i])) {
// Index of the current element
result[0] = i
// Index of the other element of the pair
result[1] = map[nums[i]]!!
break
} else {
// Save the difference of the target and the current element
// with the index of the current element
map[target - nums[i]] = i
}
}
return result
}KotlinTime Complexity For Two-Sum Problem :
चूंकि हम Array को केवल एक बार Iterate कर रहे हैं, Time Complexity O(n) होगी।
Space Complexity For Two-Sum Problem :
चूंकि हमें Array के आकार के लिए Map की आवश्यकता है, Space Complexity O(n) होगी।

Welcome to HindiTutorials, your go-to platform for learning and mastering concepts in Hindi! Our mission is to make education accessible and simple for everyone by providing high-quality tutorials on programming, technology, and various other topics.