Snippets Collections
bool isEven(Node* head){
            Node* fast = head;
            while(fast && fast->next) fast=fast->next->next;
            if(!fast )
                return true;
            return false;
    }
class Solution{
    public:
int randomPartition(int arr[], int l, int r)
    {
        int n = r-l+1;
        int pivot = rand() % n;
        swap(arr[l + pivot], arr[r]);
        return partition(arr, l, r);
    }
    int kthSmallest(int arr[], int l, int r, int k)
    {
        // If k is smaller than number of elements in array
        if (k > 0 && k <= r - l + 1)
        {
            // find a position for random partition
            int pos = randomPartition(arr, l, r);
            
            // if this pos gives the kth smallest element, then return
            if (pos-l == k-1)
                return arr[pos];
                
            // else recurse for the left and right half accordingly
            if (pos-l > k-1)  
                return kthSmallest(arr, l, pos-1, k);
            return kthSmallest(arr, pos+1, r, k-pos+l-1);
        }
    
        return INT_MAX;
    }
     
    // partitioning the array along the pivot
    int partition(int arr[], int l, int r)
    {
        int x = arr[r], i = l;
        for (int j = l; j <= r - 1; j++)
        {
            if (arr[j] <= x)
            {
                swap(arr[i], arr[j]);
                i++;
            }
        }
        swap(arr[i], arr[r]);
        return i;
    }
};
star

Fri Oct 06 2023 12:11:23 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/given-a-linked-list-reverse-alternate-nodes-and-append-at-the-end/1

#linkedlists #evenlength #o(n) #c++
star

Wed Jun 14 2023 03:15:43 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/kth-smallest-element5635/1?page

#c++ #order_statistics #kth_smallest_element #o(n) #randomized

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension