two pointers, sliding window, or hashing;
instead, it uses nested loops or multiple iterations to explore every possibility.
O(n²) or higher.
public class PairWithSum
{
public static void main(String[] args)
{
int[] arr = {2, 7, 4, 5, 1, 3};
int target = 6;
System.out.println("Pairs with given sum " + target + " are:");
boolean found = false; // flag to track if any pair is found
// Brute force approach: check all pairs
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] + arr[j] == target)
{
System.out.println(arr[i] + " + " + arr[j] + " = " + target);
found = true; // mark as found
}
}
}
if (!found)
{
System.out.println("No pairs found with the given sum.");
}
}
}
2 + 4 = 6 5 + 1 = 6
public class UnionOfArrays
{
public static void main(String[] args)
{
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
// Create a new array to store union elements
int[] union = new int[arr1.length + arr2.length];
int k = 0;
// Copy all elements from arr1
for (int i = 0; i < arr1.length; i++)
{
union[k++] = arr1[i];
}
// Add elements from arr2 that are not already present in arr1
for (int i = 0; i < arr2.length; i++)
{
boolean isDuplicate = false;
for (int j = 0; j < arr1.length; j++)
{
if (arr2[i] == arr1[j])
{
isDuplicate = true;
break;
}
}
if (!isDuplicate)
{
union[k++] = arr2[i];
}
}
System.out.println("Union of the two arrays:");
for (int i = 0; i < k; i++)
{
System.out.print(union[i] + " ");
}
}
}
Union of the two arrays: 1 2 3 4 5 6 7
for or while loops.
O(n²), O(2ⁿ), or even O(n!).
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.