Challenge

Project 2

1:

package project_2;

// first


public class SubarraySum {
void subArraySum(int arr[], int sum)
{
int n = arr.length;
for (int i = 0; i < n; i++) {
int currentSum = arr[i];

if (currentSum == sum) {
System.out.println("Sum found at indexe "
+ i);
return;
}
else {
// Try all subarrays starting with 'i'
for (int j = i + 1; j < n; j++) {
currentSum += arr[j];

if (currentSum == sum) {
System.out.println(i+ " " + j);
return;
}
}
}
}
System.out.println("No subarray found");
return;
}

public static void main(String[] args)
{
SubarraySum arraysum = new SubarraySum();
int arr[] = { 1,2,3,7,5 };
int sum = 12;
arraysum.subArraySum(arr, sum);
}
}

2:

package project_2;

public class Permutation {
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
Permutation permutation = new Permutation();
permutation.permute(str, 0, n - 1);
}
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}

3..

package project_2;

public class Btree{

static class Node
{
int data;
Node left;
Node right;
};

// function to create a new Node
static Node newNode(int data)
{
Node node = new Node();
node.data = data;
node.left = null;
node.right = null;

return node;
}

//Function to perform inorder traversal
static void inorder(Node root)
{
if (root == null)
return;

inorder(root.left);

System.out.print(root.data + " ");

inorder(root.right);
}

// to check if two BSTs are identical
static int isIdentical(Node root1,
Node root2)
{
// Check if both the trees are empty
if (root1 == null && root2 == null)
return 1;

// If any one of the tree is non-empty
// and other is empty, return false
else if (root1 != null &&
root2 == null)
return 0;
else if (root1 == null &&
root2 != null)
return 0;
else
{
// Check if current data of both trees equal
// and recursively check for left and right subtrees
if (root1.data == root2.data &&
isIdentical(root1.left, root2.left) == 1 &&
isIdentical(root1.right, root2.right) == 1)
return 1;
else
return 0;
}
}

//main method
public static void main(String[] args)
{
Node root1 = newNode(5);
Node root2 = newNode(5);
root1.left = newNode(3);
root1.right = newNode(8);
root1.left.left = newNode(2);
root1.left.right = newNode(4);

root2.left = newNode(3);
root2.right = newNode(8);
root2.left.left = newNode(2);
root2.left.right = newNode(4);

if (isIdentical(root1, root2)==1)
System.out.print("Both BSTs are identical");
else
System.out.print("BSTs are not identical");
}
}

4..

package project_2;

class Node
{
int data;
Node left, right;

public Node(int item)
{
data = item;
left = right = null;
}
}

public class BinaryTreeleavs4{
Node root;

// to get the count of leaf nodes in a binary tree
int getLeafCount()
{
return getLeafCount(root);
}

int getLeafCount(Node node)
{
if (node == null)
return 0;
if (node.left == null && node.right == null)
return 1;
else
return getLeafCount(node.left) + getLeafCount(node.right);
}
public static void main(String args[])
{
BinaryTreeleavs4 tree = new BinaryTreeleavs4();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);

/* get leaf count of the above tree */
System.out.println(" leaf of binary tree is : "
+ tree.getLeafCount());
}
}

5:

package project_2;


//Java implementation to find leaf count of a given Binary tree

/* Class containing left and right child of current
node and key value*/
//class Node{
// int data;
// Node left, right;
//
// public Node(int item)
// {
// data = item;
// left = right = null;
// }
//}

public class BinaryTree5{

//Root of the Binary Tree
Node root;

/* Function to get the count of leaf nodes in a binary tree*/
int getLeafCount()
{
return getLeafCount(root);
}

int getLeafCount(Node node)
{
if (node == null)
return 0;
if (node.left == null && node.right == null)
return 1;
else
return getLeafCount(node.left) + getLeafCount(node.right);
}

public static void main(String args[])
{
BinaryTree5 tree = new BinaryTree5();
tree.root = new Node(3);
tree.root.left = new Node(4);
tree.root.right = new Node(2);
/* get leaf count of the above tree */
System.out.println("The leaf count of binary tree is : "
+ tree.getLeafCount());
}
}

6:

package project_2;

import java.util.ArrayList;
import java.util.List;

//A Binary Tree node
//class Node {
// int data;
// Node left, right;
//
// Node(int value)
// {
// data = value;
// left = right = null;
// }
//}

public class Lowestca6 {

Node root;
private List path1 = new ArrayList<>();
private List path2 = new ArrayList<>();

// Finds the path from root node to given root of the
// tree.
int findLCA(int n1, int n2)
{
path1.clear();
path2.clear();
return findLCAInternal(root, n1, n2);
}

private int findLCAInternal(Node root, int n1, int n2)
{

if (!findPath(root, n1, path1)
|| !findPath(root, n2, path2)) {
System.out.println((path1.size() > 0)
? "n1 is present"
: "n1 is missing");
System.out.println((path2.size() > 0)
? "n2 is present"
: "n2 is missing");
return -1;
}

int i;
for (i = 0; i < path1.size() && i < path2.size();
i++) {

// System.out.println(path1.get(i) + " " +
// path2.get(i));
if (!path1.get(i).equals(path2.get(i)))
break;
}

return path1.get(i - 1);
}

// Finds the path from root node to given root of the
// tree, Stores the path in a vector path[], returns
// true if path exists otherwise false
private boolean findPath(Node root, int n,
List path)
{
// base case
if (root == null) {
return false;
}

// Store this node . The node will be removed if
// not in path from root to n.
path.add(root.data);

if (root.data == n ||
findPath(root.left, n, path) ||
findPath(root.right, n, path)) {
return true;
}

// If not present in subtree rooted with root,
// remove root from path[] and return false
path.remove(path.size() - 1);

return false;
}

// Driver code
public static void main(String[] args)
{
Lowestca6 tree
= new Lowestca6();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);

System.out.println("LCA(4, 5) = "
+ tree.findLCA(4, 5));
System.out.println("LCA(4, 6) = "
+ tree.findLCA(4, 6));
System.out.println("LCA(3, 4) = "
+ tree.findLCA(3, 4));
System.out.println("LCA(2, 4) = "
+ tree.findLCA(2, 4));
}
}

7..

package project_2;

// program to sort a linked list of 0, 1 and 2
public class LinkedListsort7 {
Node head; // head of list

class Node {
int data;
Node next;

Node(int d) {
data = d;
next = null;
}
}

void sortList() {
int count[] = { 0, 0, 0 };

Node ptr = head;

while (ptr != null) {
count[ptr.data]++;
ptr = ptr.next;
}

int i = 0;
ptr = head;
while (ptr != null) {
if (count[i] == 0)
i++;
else {
ptr.data = i;
--count[i];
ptr = ptr.next;
}
}
}

public void push(int new_data) {
Node new_node = new Node(new_data);

new_node.next = head;

head = new_node;
}

void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}

public static void main(String args[]) {
LinkedListsort7 llist = new LinkedListsort7();

llist.push(0);
llist.push(1);
llist.push(0);
llist.push(2);
llist.push(1);
llist.push(1);
llist.push(2);
llist.push(1);
llist.push(2);

System.out.println("Linked List before sorting");
llist.printList();

llist.sortList();

System.out.println("Linked List after sorting");
llist.printList();
}
}

8:

package project_2;

// program to find the first repeated character in a string
import java.util.*;

public class string8 {
static char firstRepeating(char str[]) {
// Creates an empty hashset
HashSet h = new HashSet<>();

// Traverse the input array from left to right
for (int i = 0; i <= str.length - 1; i++) {
char c = str[i];

// If element is already in hash set we will update x and then break
if (h.contains(c))
return c;

else // Else add element to hash set
h.add(c);
}

return '\0';
}

public static void main(String[] args) {
String str = "skilllync";
char[] arr = str.toCharArray();
System.out.println(firstRepeating(arr));
}
}

9:

package project_2;

// program to find given two array are equal or not
import java.util.*;

public class Arreyequal9 {
public static boolean areEqual(int arr1[], int arr2[])
{
int N = arr1.length;
int M = arr2.length;
if (N != M)
return false;

Arrays.sort(arr1);
Arrays.sort(arr2);

for (int i = 0; i < N; i++)
if (arr1[i] != arr2[i])
return false;
// if all the elements are same
return true;
}

public static void main(String[] args)
{
int arr1[] = { 3, 5, 2, 5, 2 };
int arr2[] = { 2, 3, 5, 5, 2 };

// Function call
if (areEqual(arr1, arr2))
System.out.println("Yes");
else
System.out.println("No");
}
}

10:

package project_2;

// program to sort an array according to the order defined by another array
import java.io.*;
import java.util.Arrays;

public class sortarray10 {

/*
* this one is A Binary Search based function to find index of FIRST occurrence
* of x in arr[]. If x is not present, then it returns -1
*/
static int first(int arr[], int low, int high, int x, int n) {
if (high >= low) {
int mid = low + (high - low) / 2;

if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x)
return mid;
if (x > arr[mid])
return first(arr, (mid + 1), high, x, n);
return first(arr, low, (mid - 1), x, n);
}
return -1;
}

// Sorting A1[0 to m-1] according to the order defined by A2[0 to n-1].
static void sortAccording(int A1[], int A2[], int m, int n) {

int temp[] = new int[m], visited[] = new int[m];
for (int i = 0; i < m; i++) {
temp[i] = A1[i];
visited[i] = 0;
}

Arrays.sort(temp);

int ind = 0;

for (int i = 0; i < n; i++) {
int f = first(temp, 0, m - 1, A2[i], m);

if (f == -1)
continue;

for (int j = f; (j < m && temp[j] == A2[i]); j++) {
A1[ind++] = temp[j];
visited[j] = 1;
}
}

for (int i = 0; i < m; i++)
if (visited[i] == 0)
A1[ind++] = temp[i];
}

static void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}

public static void main(String args[]) {
int A1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
int A2[] = { 2, 1, 8, 3 };
int m = A1.length;
int n = A2.length;
System.out.println("Sorted array is ");
sortAccording(A1, A2, m, n);
printArray(A1, m);
}
}

11:

12:

package project_2;
import java.io.*;
import java.util.*;

public class Mincostpath12{

static int[] dx = { -1, 0, 1, 0 };
static int[] dy = { 0, 1, 0, -1 };
static int ROW = 5;
static int COL = 5;

static class Cell
{
int x;
int y;
int distance;

Cell(int x, int y, int distance)
{
this.x = x;
this.y = y;
this.distance = distance;
}
}

// comparator for inserting cells into Priority Queue
static class distanceComparator
implements Comparator
{
public int compare(Cell a, Cell b)
{
if (a.distance < b.distance)
{
return -1;
}
else if (a.distance > b.distance)
{
return 1;
}
else {return 0;}
}
}

// method to check whether current cell is inside grid or not
static boolean isInsideGrid(int i, int j)
{
return (i >= 0 && i < ROW &&
j >= 0 && j < COL);
}

//Method to return shortest path from
//top-corner to bottom-corner in 2D grid
static int shortestPath(int[][] grid, int row,
int col)
{
int[][] dist = new int[row][col];

// Initializing distance array by INT_MAX
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
dist[i][j] = Integer.MAX_VALUE;
}
}

// Initialized source distance as initial grid position value
dist[0][0] = grid[0][0];

PriorityQueue pq = new PriorityQueue(
row * col, new distanceComparator());

// Inserting source cell to priority queue
pq.add(new Cell(0, 0, dist[0][0]));
while (!pq.isEmpty())
{
Cell curr = pq.poll();
for(int i = 0; i < 4; i++)
{
int rows = curr.x + dx[i];
int cols = curr.y + dy[i];

if (isInsideGrid(rows, cols))
{
if (dist[rows][cols] >
dist[curr.x][curr.y] +
grid[rows][cols])
{

if (dist[rows][cols] != Integer.MAX_VALUE)
{
Cell adj = new Cell(rows, cols,
dist[rows][cols]);

pq.remove(adj);
}
dist[rows][cols] = dist[curr.x][curr.y] +
grid[rows][cols];

pq.add(new Cell(rows, cols,
dist[rows][cols]));
}
}
}
}
return dist[row - 1][col - 1];
}
public static void main(String[] args)
throws IOException
{
int[][] grid = { { 31, 100, 65, 12, 18 },
{ 10, 13, 47, 157, 6 },
{ 100, 113, 174, 11, 33 },
{ 88, 124, 41, 20, 140 },
{ 99, 32, 111, 41, 20 } };

System.out.println(shortestPath(grid, ROW, COL));
}
}

13:

package project_2;
import java.util.ArrayList;
import java.util.List;

// represents anundirected graph
public class Checkstr13{

static final int CHARS = 26;

//No. of vertices
int V;

//A dynamic array of adjacency lists
List adj;
int[] in;

//Constructor
Checkstr13(int V)
{
this.V = V;
in = new int[V];
adj = new ArrayList<>(CHARS);

for(int i = 0; i < CHARS; i++)
{
adj.add(i, new ArrayList<>());
}
}

void addEdge(int v, int w)
{
adj.get(v).add(w);
in[w]++;
}

boolean isEulerianCycle()
{

if (!isSC())
return false;

// Check if in degree and out
// degree of every vertex is same
for(int i = 0; i < V; i++)
if (adj.get(i).size() != in[i])
return false;

return true;
}

boolean isSC()
{
boolean[] visited = new boolean[V];
for(int i = 0; i < V; i++)
visited[i] = false;

int n;
for(n = 0; n < V; n++)
if (adj.get(n).size() > 0)
break;
DFSUtil(n, visited);

// If DFS traversal doesn't visit all
// vertices, then return false.
for(int i = 0; i < V; i++)
if (adj.get(i).size() > 0 && !visited[i])
return false;
Checkstr13 gr = getTranspose();

for(int i = 0; i < V; i++)
visited[i] = false;

// Do DFS for reversed graph starting from first vertex
gr.DFSUtil(n, visited);

// If all vertices are not visited in
// second DFS, then return false
for(int i = 0; i < V; i++)
if (adj.get(i).size() > 0 && !visited[i])
return false;

return true;
}
void DFSUtil(int v, boolean[] visited)
{
visited[v] = true;
for(Integer i : adj.get(v))
if (!visited[i])
{
DFSUtil(i, visited);
}
}
Checkstr13 getTranspose()
{
Checkstr13 g = new Checkstr13(V);
for(int v = 0; v < V; v++)
{
for(Integer i : adj.get(v))
{
g.adj.get(i).add(v);
g.in[v]++;
}
}
return g;
}

//this function takes an of strings and returns true if the given array of strings can be chained to form cycle
static boolean canBeChained(String[] arr, int n)
{

Checkstr13 g = new Checkstr13(CHARS);

for(int i = 0; i < n; i++)
{
String s = arr[i];
g.addEdge(s.charAt(0) - 'a',
s.charAt(s.length() - 1) - 'a');
}

// given array of strings can be chained if there is an euleria cycle in the created graph
return g.isEulerianCycle();
}

//Driver code
public static void main(String[] args) throws Exception
{
String[] arr1 = { "for", "geek",
"rig", "kaf" };
int n1 = arr1.length;

System.out.println((canBeChained(arr1, n1) ?
"0 " :
"1"));

}
}

14..

package project_2;

import java.util.LinkedList;
import java.util.Queue;

public class NonReapatingCQueue14 {
final static int MAX_CHAR = 26;

static void firstNonRepeating(String str)
{
int[] charCount = new int[MAX_CHAR];

Queue q = new LinkedList();

for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);

q.add(ch);

charCount[ch - 'a']++;
while (!q.isEmpty()) {
if (charCount[q.peek() - 'a'] > 1)
q.remove();
else {
System.out.print(q.peek() + " ");
break;
}
}
if (q.isEmpty())
System.out.print(-1 + " ");
}
System.out.println();
}

public static void main(String[] args)
{
String str = "aabc";
firstNonRepeating(str);
}
}

15:

package project_2;
//Java implementation of the approach
import java.util.*;

public class Fadjucent15{

static boolean isPossible(char[] str)
{
Map freq = new HashMap<>();

int max_freq = 0;
for (int j = 0; j < (str.length); j++) {
if (freq.containsKey(str[j])) {
freq.put(str[j], freq.get(str[j]) + 1);
if (freq.get(str[j]) > max_freq)
max_freq = freq.get(str[j]);
}
else {
freq.put(str[j], 1);
if (freq.get(str[j]) > max_freq)
max_freq = freq.get(str[j]);
}
}

if (max_freq <= (str.length - max_freq + 1))
return true;
return false;
}

public static void main(String[] args)
{
String str = "bbbbbbb";

if (isPossible(str.toCharArray()))
System.out.println("1");
else
System.out.println("0");
}
}

16..

17..

package project_2;

public class arrysum17{

static int maxSumIS(int arr[], int n)
{
int i, j, max = 0;
int msis[] = new int[n];


for (i = 0; i < n; i++)
msis[i] = arr[i];

for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] > arr[j] &&
msis[i] < msis[j] + arr[i])
msis[i] = msis[j] + arr[i];

for (i = 0; i < n; i++)
if (max < msis[i])
max = msis[i];

return max;
}

public static void main(String args[])
{
int arr[] = new int[]{1, 101, 2, 3, 100, 4, 5};
int n = arr.length;
System.out.println("Sum of maximum sum "+
"increasing subsequence is "+
maxSumIS(arr, n));
}
}

18:

package project_2;


import java.io.*;

public class Noofhopesdp18{
// Function returns count of ways to cover 'dist'
static int printCountDP(int dist)
{
int[] count = new int[dist+1];
count[0] = 1;
if(dist >= 1)
count[1] = 1;
if(dist >= 2)
count[2] = 2;

// Fill the count array in bottom up manner
for (int i=3; i<=dist; i++)
count[i] = count[i-1] + count[i-2] + count[i-3];

return count[dist];
}

// driver program
public static void main (String[] args)
{
int dist = 1;
System.out.println(printCountDP(dist));
}
}

19:

package project_2;
// program to find maximum number of meetings
import java.util.*;

//Comparator function which can compare the ending time of the meeting ans
class mycomparator implements Comparator {
@Override public int compare(meeting o1, meeting o2)
{
if (o1.end < o2.end) {

// Return -1 if second object is
// bigger than first
return -1;
}
else if (o1.end > o2.end)

// Return 1 if second object is
// smaller than first
return 1;

return 0;
}
}

//Custom class for storing starting time,finishing time and position of meeting.
class meeting {
int start;
int end;
int pos;

meeting(int start, int end, int pos)
{
this.start = start;
this.end = end;
this.pos = pos;
}
}

public class greedy19 {

// Function for finding maximum meeting in one room
public static void maxMeeting(ArrayList al,
int s)
{

// Initialising an arraylist for storing answer
ArrayList m = new ArrayList<>();

int time_limit = 0;

mycomparator mc = new mycomparator();

// Sorting of meeting according to
// their finish time.
Collections.sort(al, mc);

// Initially select first meeting.
m.add(al.get(0).pos);

// time_limit to check whether new meeting can be conducted or not.
time_limit = al.get(0).end;

// Checking for all meeting whether it can be selected or not.
for (int i = 1; i < al.size(); i++) {
if (al.get(i).start > time_limit) {

// Add selected meeting to arraylist
m.add(al.get(i).pos);

// Update time limit
time_limit = al.get(i).end;
}
}

// Print final selected meetings.
for (int i = 0; i < m.size(); i++)
System.out.print(m.get(i) + 1 + " ");
}
public static void main(String[] args)
{

int s[] = { 1, 3, 0, 5, 8, 5 };

int f[] = { 2, 4, 6, 7, 9, 9 };

ArrayList meet = new ArrayList<>();
for (int i = 0; i < s.length; i++)

// Creating object of meeting
// and adding in the list
meet.add(new meeting(s[i], f[i], i));

// Function call
maxMeeting(meet, meet.size());
}
}

20.

package project_2;
//Java program to find the largest number that can be formed from given sum of digits and number of digits

public class Largestnum20{
// Function to print the largest possible number with digit sum 's' and 'm' number of digits
static void findLargest(int m, int s)
{
// If sum of digits is 0, then a number is possible
// only if number of digits is 1
if (s == 0)
{
System.out.print(m == 1 ? "Largest number is 0" : "Not possible");

return ;
}

// Sum greater than the maximum possible sum
if (s > 9*m)
{
System.out.println("Not possible");
return ;
}

// Create an array to store digits of result
int[] res = new int[m];

// Fill from most significant digit to least
// significant digit
for (int i=0; i {
if (s >= 9)
{
res[i] = 9;
s -= 9;
}
else
{
res[i] = s;
s = 0;
}
}

System.out.print("Largest number is ");
for (int i=0; i System.out.print(res[i]);
}

public static void main (String[] args)
{
int s = 9, m = 2;
findLargest(m, s);
}
}

21..

package project_2;
//Java program to find the largest number that can be formed from given sum of digits and number of digits

public class Largestnum21{
// Function to print the largest possible number with digit sum 's' and 'm' number of digits
static void findLargest(int m, int s)
{
// If sum of digits is 0, then a number is possible
// only if number of digits is 1
if (s == 0)
{
System.out.print(m == 1 ? "Largest number is 0" : "Not possible");

return ;
}

// Sum greater than the maximum possible sum
if (s > 9*m)
{
System.out.println("Not possible");
return ;
}

// Create an array to store digits of result
int[] res = new int[m];

// Fill from most significant digit to least
// significant digit
for (int i=0; i {
if (s >= 9)
{
res[i] = 9;
s -= 9;
}
else
{
res[i] = s;
s = 0;
}
}

System.out.print("Largest number is ");
for (int i=0; i System.out.print(res[i]);
}

public static void main (String[] args)
{
int s = 9, m = 2;
findLargest(m, s);
}
}

22.

package project_2;

//Java program to find the length of the
//longest substring without repeating
//characters
import java.io.*;
import java.util.*;

public class Longestsubstring{

//This function returns true if all characters in
//str[i..j] are distinct, otherwise returns false
public static Boolean areDistinct(String str,
int i, int j)
{

// Note : Default values in visited are false
boolean[] visited = new boolean[26];

for(int k = i; k <= j; k++)
{
if (visited[str.charAt(k) - 'a'] == true)
return false;

visited[str.charAt(k) - 'a'] = true;
}
return true;
}

//Returns length of the longest substring
//with all distinct characters.
public static int longestUniqueSubsttr(String str)
{
int n = str.length();

// Result
int res = 0;

for(int i = 0; i < n; i++)
for(int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = Math.max(res, j - i + 1);

return res;
}

public static void main(String[] args)
{
String str = "abababcdefababcdab";
System.out.println("The input string is " + str);

int len = longestUniqueSubsttr(str);

System.out.println("The length of the longest " +
"non-repeating character " +
"substring is " + len);
}
}

23:

package project_2;
//Java program to find smallest
//window containing
//all characters of a pattern.

public class Smallestwindow23 {
static final int no_of_chars = 256;

// Function to find smallest
// window containing
// all characters of 'pat'
static String findSubString(String str, String pat)
{
int len1 = str.length();
int len2 = pat.length();

// Checking if string's length is
// less than pattern's
// length. If yes then no such
// window can exist
if (len1 < len2) {
System.out.println("No such window exists");
return "";
}

int hash_pat[] = new int[no_of_chars];
int hash_str[] = new int[no_of_chars];

// Storeing occurrence ofs
// characters of pattern
for (int i = 0; i < len2; i++)
hash_pat[pat.charAt(i)]++;

int start = 0, start_index = -1,
min_len = Integer.MAX_VALUE;

// Start traversing the string
// Count of characters
int count = 0;
for (int j = 0; j < len1; j++) {

// Counting occurrence of characters
// of string
hash_str[str.charAt(j)]++;

if (hash_str[str.charAt(j)]
<= hash_pat[str.charAt(j)])
count++;

// If all the characters are matched
if (count == len2) {
while (hash_str[str.charAt(start)]
> hash_pat[str.charAt(start)]
|| hash_pat[str.charAt(start)]
== 0) {

if (hash_str[str.charAt(start)]
> hash_pat[str.charAt(start)])
hash_str[str.charAt(start)]--;
start++;
}

int len_window = j - start + 1;
if (min_len > len_window) {
min_len = len_window;
start_index = start;
}
}
}

if (start_index == -1) {
System.out.println("No such window exists");
return "";
}

return str.substring(start_index,
start_index + min_len);
}


public static void main(String[] args)
{
String str = "timetopractice";
String pat = "toc";

System.out.print(findSubString(str, pat));
}
}

24:

package project_2;

//Java Program to find whether a
//no is power of two
import java.lang.Math;

public class powoftwo24 {
static boolean isPowerOfTwo(int n)
{
if (n == 0)
return false;

return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(
((Math.log(n) / Math.log(2)))));
}

public static void main(String[] args)
{
// Function call
if (isPowerOfTwo(1))
System.out.println("Yes");
else
System.out.println("No");

if (isPowerOfTwo(98))
System.out.println("Yes");
else
System.out.println("No");
}
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.